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

后端 未结 9 2118
迷失自我
迷失自我 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 11:51
    _.isEmpty(_.xor(array1, array2))
    
    0 讨论(0)
  • 2020-12-20 11:58

    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);
    }
    
    0 讨论(0)
  • 2020-12-20 12:03

    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.

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

    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
    
    0 讨论(0)
  • 2020-12-20 12:06

    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.

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

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