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?
In my case compared arrays contain only numbers and strings. This function will show you if arrays contain same elements.
Let's test it!
If the array is plain and the order is matter so this two lines may help
Reduce walks through one of array and returns 'false' if at least one element of 'a' is nor equial to element of 'b' Just wrap this into function
Even though this has a lot of answers, one that I believe to be of help:
It is not stated in the question how the structure of the array is going to look like, so If you know for sure that you won't have nested arrays nor objects in you array (it happened to me, that's why I came to this answer) the above code will work.
What happens is that we use spread operator ( ... ) to concat both arrays, then we use Set to eliminate any duplicates. Once you have that you can compare their sizes, if all three arrays have the same size you are good to go.
This answer also ignores the order of elements, as I said, the exact situation happened to me, so maybe someone in the same situation might end up here (as I did).
Edit1.
Answering Dmitry Grinko's question: "Why did you use spread operator ( ... ) here - ...new Set ? It doesn't work"
Consider this code:
You'll get
In order to work with that value you'd need to use some Set properties (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). On the other hand, when you use this code:
You'll get
That's the difference, the former would give me a Set, it would work too as I could get the size of that Set, but the latter gives me the array I need, what's more direct to the resolution.
On the same lines as JSON.encode is to use join().
Only problem is if you care about types which the last comparison tests. If you care about types, you will have to loop.
If the order should remain the same, than it is just a loop, no sort is needed.
It's unclear what you mean by "identical". For example, are the arrays
a
andb
below identical (note the nested arrays)?Here's an optimized array comparison function that compares corresponding elements of each array in turn using strict equality and does not do recursive comparison of array elements that are themselves arrays, meaning that for the above example,
arraysIdentical(a, b)
would returnfalse
. It works in the general case, which JSON- andjoin()
-based solutions will not:Comparing 2 arrays:
calling function