compare 2 array Js code example

Example 1: es6 compare two arrays

let difference = arrA.filter(x => !arrB.includes(x));

Example 2: 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 3: compare arrays javascript

// For regular 1D array
const array1 = [1,2,3,4]
const array2 = [1,2,3,4]

array1.join() === array2.join()
// '1,2,3,4' === '1,2,3,4'

// For anything more complex
const array3 = [1,2,3,[1,2,3]]
const array4 = [1,2,3,[1,2,3]]

JSON.stringify(array3) === JSON.stringify(array4)

Example 4: javascript find matching elements in two arrays

let firstArray = ["One", "Two", "Three", "Four", "Five"];
let secondArray = ["Three", "Four"];

let map = {};
firstArray.forEach(i => map[i] = false);
secondArray.forEach(i => map[i] === false && (map[i] = true));
let jsonArray = Object.keys(map).map(k => ({ name: k, matched: map[k] }));

Example 5: comparing two arrays in javascript

const arr1 = [1, 2, 3];
const arr2 = [1, 3, 3];

if (arr1.length !== arr2.length) return console.log("false");
for (let i = 0; i < arr1.length; i++) {
    for (let j = 0; j < arr2.length; j++) {
        if (arr1[i] === arr2[j]) {
            console.log("yes match", arr1[i], arr2[j]);
            continue;
        }
        console.log("no match", arr1[i], arr2[j]);
    }
}