Example 1: diff two arrays javascript
function diffArray(arr1, arr2) {
return arr1
.concat(arr2)
.filter(item => !arr1.includes(item) || !arr2.includes(item));
}
Example 2: es6 compare two arrays
let difference = arrA.filter(x => !arrB.includes(x));
Example 3: comparing 2 array
const arr1 = [1, 2, 3];
const arr2 = [1, 3, 3];
if (arr1.length !== arr2.length) return console.log("false");
let j = 0
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] === arr2[j]) {
console.log("yes match", arr1[i], arr2[j]);
}
else{
console.log("no match", arr1[i], arr2[j]);
}
j++;
}
Example 4: javascript compare two arrays of objects get same elements
var result = result1.filter(function (o1) {
return result2.some(function (o2) {
return o1.id === o2.id;
});
});
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));
Example 5: javascript compare arrays
Array.prototype.equals = function(arr2) {
return (
this.length === arr2.length &&
this.every((value, index) => value === arr2[index])
);
};
[1, 2, 3].equals([1, 2, 3]);
[1, 2, 3].equals([3, 6, 4, 2]);
Example 6: 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]);