Array comparison

suggest change

For simple array comparison you can use JSON stringify and compare the output strings:

JSON.stringify(array1) === JSON.stringify(array2)
Note: that this will only work if both objects are JSON serializable and do not contain cyclic references. It may throw TypeError: Converting circular structure to JSON

You can use a recursive function to compare arrays.

function compareArrays(array1, array2) { 
  var i, isA1, isA2;
  isA1 = Array.isArray(array1);
  isA2 = Array.isArray(array2);
  
  if (isA1 !== isA2) { // is one an array and the other not?
    return false;      // yes then can not be the same
  }
  if (! (isA1 && isA2)) {      // Are both not arrays 
    return array1 === array2;  // return strict equality
  }
  if (array1.length !== array2.length) { // if lengths differ then can not be the same
    return false;
  }
  // iterate arrays and compare them
  for (i = 0; i < array1.length; i += 1) {
    if (!compareArrays(array1[i], array2[i])) { // Do items compare recursively
      return false;
    }           
  }
  return true; // must be equal
}

WARNING: Using the above function is dangerous and should be wrapped in a try catch if you suspect there is a chance the array has cyclic references (a reference to an array that contains a reference to itself)

a = [0] ;
a[1] = a;
b = [0, a]; 
compareArrays(a, b); // throws RangeError: Maximum call stack size exceeded
Note: The function uses the strict equality operator === to compare non array items {a: 0} === {a: 0} is false

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents