js find equal elements in two arrays code example

Example 1: check if 2 arrays are equal javascript

const a = [1, 2, 3];
const b = [4, 5, 6];
const c = [1, 2, 3];

function arrayEquals(a, b) {
  return Array.isArray(a) &&
    Array.isArray(b) &&
    a.length === b.length &&
    a.every((val, index) => val === b[index]);
}

arrayEquals(a, b); // false
arrayEquals(a, c); // true

Example 2: javascript find matching elements in two arrays

const intersection = array1.filter(element => array2.includes(element));

Example 3: 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] }));