Example 1: javascript difference between two arrays
let difference = arr1.filter(x => !arr2.includes(x));
Example 2: es6 compare two arrays
let difference = arrA.filter(x => !arrB.includes(x));
Example 3: 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]); // true
[1, 2, 3].equals([3, 6, 4, 2]); // false
Example 4: best way compare arrays javascript
// To compare arrays (or any other object):
// Simple Array Example:
const array1 = ['potato', 'banana', 'soup']
const array2 = ['potato', 'orange', 'soup']
array1 === array2;
// Returns false due to referential equality
JSON.stringify(array1) === JSON.stringify(array2);
// Returns true
// Another Example:
const deepArray1 = [{test: 'dummy'}, [['woo', 'ya'], 'weird']]
const deepArray2 = [{test: 'dummy'}, [['woo', 'ya'], 'weird']]
deepArray1 === deepArray2;
// Returns false due to referential equality
JSON.stringify(deepArray1) === JSON.stringify(deepArray2);
// Returns true
Example 5: javascript Compare two arrays regardless of order
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
// Examples
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
Example 6: how to compare two arrays javascript
function arraysAreIdentical(arr1, arr2){
if (arr1.length !== arr2.length) return false;
for (var i = 0, len = arr1.length; i < len; i++){
if (arr1[i] !== arr2[i]){
return false;
}
}
return true;
}