compare 2 array values in javascript code example
Example 1: javascript find matching elements in two arrays
const intersection = array1.filter(element => array2.includes(element));
Example 2: 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;
}
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] }));
Example 4: compare between two arrays javascript
const equals = (a, b) => JSON.stringify(a) === JSON.stringify(b);
let arr1 = ['1','2'];
let arr2 = ['1','2'];
equals(arr1,arr2)