Take the 2-minute tour ×

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?

share|improve this question

6 Answers 6

up vote 5 down vote accepted

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

share|improve this answer
That's almost exactly what I'm looking for. Is there a way to ignore the order of the array elements? –  Kevin Whitaker Apr 11 '12 at 17:09
@KevinWhitaker: Yep! Updated answer. –  Dan Tao Apr 11 '12 at 17:27
Difference function is asymmetrical: you are comparing all the arrays to the 0th one, but not in the other direction. If for example the 0th array is empty then the difference returns nothing in all cases yet they are not all the same. –  peterfoldi Apr 11 '12 at 17:34
@peterfoldi: Wow, good point. Fixed (I think)! –  Dan Tao Apr 11 '12 at 17:42

Why not intersection? (if you really want to use some Underscore functions for this) http://documentcloud.github.com/underscore/#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.

share|improve this answer

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

This will return true if they are the same and false if they are not.

share|improve this answer

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]
share|improve this answer
or for every set of value pairs, return _.union(x).length == 1; for arbitrary numbers of arrays compared. –  Sam Simmons Oct 23 '13 at 16:23

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
share|improve this answer
_.isEmpty(_.xor(array1, array2))
share|improve this answer

Your Answer


