Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 758
Hcabnettek Avatar asked Apr 19 '11 20:04

Hcabnettek


2 Answers

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

_.difference([0, 1, 3, 9], [1, 3]); // => [0, 9]
like image 173
ultrageek Avatar answered Oct 14 '22 15:10

ultrageek


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

like image 45
Raynos Avatar answered Oct 14 '22 15:10

Raynos