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:


Arrays:
* Syntax
* Array comparison

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde