javascript how to compare two arrays code example

Example 1: diff two arrays javascript

function diffArray(arr1, arr2) {
  return arr1
    .concat(arr2)
    .filter(item => !arr1.includes(item) || !arr2.includes(item));
}

Example 2: 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 3: 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 4: 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)

Tags:

Php Example