I have an array of arrays, which looks something like this:
[[\"Some string\", \"Some other string\"],[\"Some third string\", \"some fourth string\"]]
_.isEmpty(_.xor(array1, array2))
My implementation with http://underscorejs.org/
/**
* Returns true if the arrays are equal
*
* @param {Array} array1
* @param {Array} array2
* @returns {boolean}
*/
equal: function ( array1, array2 )
{
return ( array1.length === array2.length)
&& (array1.length === _.intersection( array1, array2 ).length);
}
Use underscore to determine the difference between the two, and check the length of the array. An easy way to do this would be:
_.isEmpty(_.difference(array1, array2)) && _.isEmpty(_.difference(array2, array1))
This will return true
if they are the same and false
if they are not.
If you don't need to know which elements are unequal, use transitivity:
function allEqual(list) {
return _.all(list.slice(1), _.partial(_.isEqual, list[0]));
}
allEqual([2, 2, 2, 2]) //=> true
allEqual([2, 2, 3, 2]) //=> false
allEqual([false]) //=> true
allEqual([]) //=> true
Why not intersection? (if you really want to use some Underscore functions for this) http://underscorejs.org/#intersection
If the arrays are of the same length, and the length of the intersection equals to the length of the arrays, then they all contain the same values.
If you want to check that the elements are the same and in the same order, I would go with:
arrayEq = function(a, b) {
return _.all(_.zip(a, b), function(x) {
return x[0] === x[1];
});
};
Even more neatly in coffeescript:
arrayEq = (a,b) ->
_.all _.zip(a,b), (x) -> x[0]==x[1]