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?
Javascript Useful Snippets — allEqual() In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise.
I think the simplest way to do this is to create a loop to compare the each value to the next. As long as there is a break in the "chain" then it would return false. If the first is equal to the second, the second equal to the third and so on, then we can conclude that all elements of the array are equal to each other.
Using List contains() method. We can use Arrays class to get the list representation of the array. Then use the contains() method to check if the array contains the value.
Check if two arrays are equal or not using Sorting Then linearly compare elements of both the arrays. If all are equal then return true, else return false.
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.
My preference:
_.isEqual(_.sortBy(first), _.sortBy(second))
And if order matters:
_(first).isEqual(second)
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With