I'd like to compare two arrays... ideally, efficiently. Nothing fancy, just true
if they are identical, and false
if not. Not surprisingly, the comparison operator doesn't seem to work.
var a1 = [1,2,3];
var a2 = [1,2,3];
console.log(a1==a2); // Returns false
console.log(JSON.stringify(a1)==JSON.stringify(a2)); // Returns true
JSON encoding each array does, but is there a faster or "better" way to simply compare arrays without having to iterate through each value?
This function compares two arrays of arbitrary shape and dimesionality:
for single dimension array you can simply use:
arr1.sort().toString() == arr2.sort().toString()
this will also take care of array with mismatched index.
We could do this the functional way, using
every
(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/every)////// OR ///////
My solution compares Objects, not Arrays. This would work in the same way as Tomáš's as Arrays are Objects, but without the Warning:
Hope this helps you or anyone else searching for an answer.
To compare arrays, loop through them and compare every value:
Comparing arrays:
Usage:
You may say "But it is much faster to compare strings - no loops..." well, then you should note there ARE loops. First recursive loop that converts Array to string and second, that compares two strings. So this method is faster than use of string.
I believe that larger amounts of data should be always stored in arrays, not in objects. However if you use objects, they can be partially compared too.
Here's how:
Comparing objects:
I've stated above, that two object instances will never be equal, even if they contain same data at the moment:
This has a reason, since there may be, for example private variables within objects.
However, if you just use object structure to contain data, comparing is still possible:
However, remember that this one is to serve in comparing JSON like data, not class instances and other stuff. If you want to compare mor complicated objects, look at this answer and it's superlong function.
To make this work with
Array.equals
you must edit the original function a little bit:I made a little test tool for both of the functions.
Bonus: Nested arrays with
indexOf
andcontains
Samy Bencherif has prepared useful functions for the case you're searching for a specific object in nested arrays, which are available here: https://jsfiddle.net/SamyBencherif/8352y6yw/