问题
I have an array of arrays, which looks something like this:
[["Some string", "Some other string"],["Some third string", "some fourth string"]]
I think I can use the _.all
method in Underscore to determine if all of the arrays match 100% (that is all of their values match), but I'm not sure how to write the required iterator to run the check.
Anyone have an idea?
回答1:
Try this guy (order-independent):
function allArraysAlike(arrays) {
return _.all(arrays, function(array) {
return array.length == arrays[0].length && _.difference(array, arrays[0]).length == 0;
});
}
This is assuming you want all of the arrays to contain all the same elements in the same order as one another (so for your example input the function should return false
).
回答2:
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.
回答3:
My preference:
_.isEqual(_.sortBy(first), _.sortBy(second))
And if order matters:
_(first).isEqual(second)
回答4:
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.
回答5:
_.isEmpty(_.xor(array1, array2))
回答6:
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]
回答7:
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);
}
回答8:
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
回答9:
I can't comment on Dan Tao's answer, small change to skip checking of first array against itself (unnecessary _.difference call)
function allArraysAlike(arrays) {
return _.all(arrays, function(array) {
if(array === arrays[0]) return true;
return array.length == arrays[0].length && _.difference(array, arrays[0]).length == 0;
});
}
来源:https://stackoverflow.com/questions/10110510/underscore-js-determine-if-all-values-in-an-array-of-arrays-match