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 is how i did it.
Extending Tomáš Zato idea. Tomas's Array.prototype.compare should be infact called Array.prototype.compareIdentical.
It passes on:
But fails on:
Here is better (in my opinion) version:
http://jsfiddle.net/igos/bcfCY/
Building off Tomáš Zato's answer, I agree that just iterating through the arrays is the fastest. Additionally (like others have already stated), the function should be called equals/equal, not compare. In light of this, I modified the function to handle comparing arrays for similarity - i.e. they have the same elements, but out of order - for personal use, and thought I'd throw it on here for everyone to see.
This function takes an additional parameter of strict that defaults to true. This strict parameter defines if the arrays need to be wholly equal in both contents and the order of those contents, or simply just contain the same contents.
Example:
I've also written up a quick jsfiddle with the function and this example:
http://jsfiddle.net/Roundaround/DLkxX/
This compares 2 unsorted arrays:
Choose each from [a] and loop through all from [b]: Result: 1, 5
Herer's my solution:
Works with any nested data structure, and obviously ignores objects' methods. Don't even think of extending Object.prototype with this method, when I tried this once, jQuery broke ;)
For most arrays it's still faster than most of serialization solutions. It's probably the fastest compare method for arrays of object records.