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

倖福魔咒の 提交于 2019-12-20 10:27:40

问题


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

I would like => [0,9] returned

It appears _without's 2nd arg is a list of values, not an array. Anyone out there know if underscore has the specific function I'm looking for? Or can I take an exisitng array and covert it to values the function expects.

Thanks,
~ck in San Diego


回答1:


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




回答2:


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

_.difference([0, 1, 3, 9], [1, 3]); // => [0, 9]



回答3:


var result = _.reject([0, 1, 3, 9], function(num) {
                return _.include([1, 3], num);
            });



回答4:


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]


来源:https://stackoverflow.com/questions/5722254/underscore-js-is-there-a-function-that-produces-an-array-thats-the-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!