Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

underscore.js - Determine if all values in an array of arrays match

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?

like image 778
Kevin Whitaker Avatar asked Apr 11 '12 16:04

Kevin Whitaker


People also ask

How do you check if all values in an array are equal JS?

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.

How do you check if all the elements of array are equal?

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.

How do you check if an array contains a value from another array?

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.

How do I check if an array is a match?

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.


3 Answers

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.

like image 56
peterfoldi Avatar answered Oct 21 '22 06:10

peterfoldi


My preference:

_.isEqual(_.sortBy(first), _.sortBy(second))

And if order matters:

_(first).isEqual(second)
like image 23
paulmelnikow Avatar answered Oct 21 '22 04:10

paulmelnikow


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).

like image 14
Dan Tao Avatar answered Oct 21 '22 04:10

Dan Tao