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?
If you are using a testing framework like Mocha with the Chai assertion library, you can use deep equality to compare arrays.
This should return true only if the arrays have equal elements at corresponding indices.
If they are two arrays of numbers or strings only, this is a quick one-line one
this script compares Object, Arrays and multidimensional array
first line checks whether it's a primitive type. if so it compares the two parameters.
if they are Objects. it iterates over the Object and check every element recursivly.
Usage:
In the spirit of the original question:
I have been running performance tests on some of the more simple suggestions proposed here with the following results (fast to slow):
while (67%) by Tim Down
every (69%) by user2782196
reduce (74%) by DEIs
join & toString (78%) by Gaizka Allende & vivek
half toString (90%) by Victor Palomo
stringify (100%) by radtek
Another approach with very few code (using Array reduce and Array includes):
If you want to compare also the equality of order:
The
length
check ensures that the set of elements in one array isn't just a subset of the other one.The reducer is used to walk through one array and search for each item in other array. If one item isn't found the reduce function returns
false
.This I think is the simplest way to do it using JSON stringify, and it may be the best solution in some situations:
This converts the objects
a1
anda2
into strings so they can be compared. The order is important in most cases, for that can sort the object using a sort algorithm shown in one of the above answers.Please do note that you are no longer comparing the object but the string representation of the object. It may not be exactly what you want.