darkness darkness - 7 months ago 17
Javascript Question

compare 2 arrays and get those variables did not match

var array1 = ["display1"];
var array2 = ["display1", "display2", "display3"];

Array.prototype.compare = function(testArr) {
if (this.length != testArr.length) return false;
for (var i = 0; i < testArr.length; i++) {
if (this[i].compare) {
if (!this[i].compare(testArr[i])) return false;
}
if (this[i] !== testArr[i]) return false;
}
return true;
}

if(!array1.compare(array2)) {
alert("is not match");
// get all un-matched variable.
}else{
alert("matched");
}


my intetion is to compare 2 array to each other , and get all those un-matched variable out , this code all compare the see if they are matched or not.

how do i get all the un-matched variable ??

so this result will be ["display2", "display3"];

Answer

You could use a temporary object with count the given values of array1 and array2 and filter if the value has count 1.

function xxx(a1, a2) {
    var a3 = a1.concat(a2),
        temp = Object.create(null);

    a3.forEach(function (a) {
        temp[a] = (temp[a] || 0) + 1;
    });
    return a3.filter(function (a) {
        return temp[a] === 1;
    });
}

var array1 = ["display1"],
    array2 = ["display1", "display2", "display3"],
    array3 = xxx(array1, array2);

document.write('<pre>' + JSON.stringify(array3, 0, 4) + '</pre>');

ES6

function xxx(a1, a2) {
    var a3 = a1.concat(a2),
        temp = Object.create(null);

    a3.forEach(a => temp[a] = (temp[a] || 0) + 1);
    return a3.filter(a => temp[a] === 1);
}

var array1 = ["display1"],
    array2 = ["display1", "display2", "display3"],
    array3 = xxx(array1, array2);

document.write('<pre>' + JSON.stringify(array3, 0, 4) + '</pre>');