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

后端 未结 9 2119
迷失自我
迷失自我 2020-12-20 11:30

I have an array of arrays, which looks something like this:

[[\"Some string\", \"Some other string\"],[\"Some third string\", \"some fourth string\"]]


        
相关标签:
9条回答
  • 2020-12-20 12:09

    My preference:

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

    And if order matters:

    _(first).isEqual(second)
    
    0 讨论(0)
  • 2020-12-20 12:13

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

    0 讨论(0)
  • 2020-12-20 12:14

    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;
        });
    }
    
    0 讨论(0)
提交回复
热议问题