MOCKSTACKS
EN
Questions And Answers

More Tutorials









Javascript Array comparison

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


JSON.stringify(array1) === JSON.stringify(array2)

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
}

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,1] ;
b = [0,1];
compareArrays(a, b);

Output

true

a = [0] ;
a[1] = a;
b = [0, a];
compareArrays(a, b);

Output

throws RangeError: Maximum call stack size exceeded

The function uses the strict equality operator === to compare non array items {a: 0} === {a: 0} is false

Conclusion

In this page (written and validated by ) you learned about Javascript Array comparison . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript Reversing arrays.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.