compare two arrays for equality javascript code example
Example 1: javascript get array difference
function arrayDiff (a1, a2) {
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}
console.log(arrayDiff(['red', 'white','green'], [ 'red','white', 'blue']));
Example 2: javascript Compare two arrays regardless of order
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
isEqual([1, 2, 3], [1, 2, 3]);
isEqual([1, 2, 3], [1, '2', 3]);