underscore.js - Is there a function that produces an array thats the difference of two arrays?

前端 未结 4 1066
难免孤独
难免孤独 2021-02-04 03:28

Looking for a function in underscore.js that will take 2 arrays and return a new array of unique values? Something like _without

_.without([0, 1, 3, 9], [1, 3])         


        
相关标签:
4条回答
  • 2021-02-04 03:40

    _.without.apply(_, [arr1].concat(arr2))

    [[0, 1, 3, 9]].concat([1, 3]) is [[0, 1, 3, 9], 1, 3];

    _.without.apply(_, [[0, 1, 3, 9], 1, 3]) is _.without([0, 1, 3, 9], 1, 3)

    You've got a perfectly good _.without method. So just convert an array into a list of values you can pass into a function. This is the purpose of Function.prototype.apply

    0 讨论(0)
  • var result = _.reject([0, 1, 3, 9], function(num) {
                    return _.include([1, 3], num);
                });
    
    0 讨论(0)
  • 2021-02-04 04:02

    The _.difference function should give you what you're looking for:

    _.difference([0, 1, 3, 9], [1, 3]); // => [0, 9]
    
    0 讨论(0)
  • 2021-02-04 04:03

    Lo-Dash is extended Underscore and here is what you need: http://lodash.com/docs#xor

    _.xor

    Creates an array that is the symmetric difference of the provided arrays. See http://en.wikipedia.org/wiki/Symmetric_difference.

    _.xor([1, 2, 3], [5, 2, 1, 4]);
    // → [3, 5, 4]
    
    0 讨论(0)
提交回复
热议问题