Primordial topic, I know, but can anyone please comment on the following algorithm for comparing two ES5 arrrays:
function equal_arrays(a, b) {
"use strict";
var c = 0;
return a.every(function (e) {
return e === b[c++];
});
}
I think this is very clean and obvious use of [].every(), to quickly compare two arrays? I have that nagging "surely it can not be that simple ?" feeling about it ?
NOTE: two arrays are equal when they contain all elements in the same position strictly equal to each other. So both the element index and element value have to be exactly equal. Values of different types are considered not equal. Sparse arrays are also compared.
TEST CASES:
equal_arrays([],[]) ; // => true
equal_arrays([1,2],[1,2]) ; // => true
equal_arrays([1,,2],[1,,2]) ; // => true
equal_arrays([,],[,]); // => true
equal_arrays([1,,3,,,],[1,,3,,,]); // => true
Uses cases yielding => false, one can imagine herself. Comparing non-arrays is a syntax error.
Many thanks to the well meaning and helpful contributors. It appears that the "best" (there is never such a thing) implementation is this:
function has(element, index)
{
return this[index] === element;
}
function equal_arrays(a, b)
{
return (a.length === b.length) && a.every(has, b) && b.every(has, a);
}
@tom's implementation of the two-way every() which is necessary sp that test cases like this one work:
equal_arrays([1,,3],[1,2,3]); //=> false
Once again thanks ...
c. Just define a second parameter to theevery()callback, and you'll get your index. Other than that, if you want a strict equality evaluation, then yes, it's valid..every()will skip indices that are not defined in sparse arrays. So ifahas a hole in it, andbdoes not, it won't bother checking the index where the hole is. So ifbhas something defined, you'll get a false positive. Also a good idea to test the lengths first.numberandstringvalues. For arrays of objects, it'll expect object references to be exactly the same in order to be equal (which may be OK).ais shorter thanb, and the items inaare the same the first items inb, the method will give a false positive.