_.without to accept array as second argument #104

Closed
ondrejhlavacek opened this Issue Jan 21, 2011 · 9 comments

Comments

Projects
None yet
8 participants

The current definition of _.without accept array as the first argument and then any number of following args. I know it might get tricky, but it would be helpful, if I could pass another array as argument.

The new functionality would work as
_.without([1,2,3], [1, 2])
returns
[3]

As far as I know _.without does not work deep, so it might not be overcomplicated -
_.without([1,2,3,[1]], [1], 1)
returns
[2, 3, [1]]

Owner

jashkenas commented Jan 21, 2011

Fortunately, JavaScript has a built-in way to pass a function any number of arguments.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/apply

_.without.apply(_, [1, 2, 3], [1, 2])

Sure thing! Stupid me, how could I forget...

It seems that it needs to be called like this

_.without.apply(_, [[1,2,3], 1, 2])

Which makes it just a little bit complicated (unshifting the exlusion array with the original array).

UPDATE: I created a new ticket for this issue: https://github.com/documentcloud/underscore/issues/issue/118

I have to agree to both of you: to Jeremy for keeping the _.without signature consistent and to Ondrey for finding Jeremys proposed workaround a bit hackish (it doesn't seem to work for me too).

Thus, I want to propose the introduction of two new underscore functions: _.difference(*arrays) and _.symdifference(a,b): difference would find out all elements in from the first array that don't appear in the other supplied arrays, where _.symdifference() would return those elements that are either in a or in b but not in both.

The "inspiration" for these functions comes from the python set datatype and IMHO they shouldn't be just limited to arrays, since they are also applicable to objects.

Just a quick way of writing it with underscore: .without.apply(, [x].concat(y)), will return array of values in x without the values in y.

reggi commented Dec 17, 2014

@rubenstolk's answer works except he didn't comment his code out so the underscores interpreted as italic. For future generations! 🚃 🚀 🌈 🙌

_.without.apply(_, [originalArray].concat(removeArray));

I think Github wasn't doing that 2 years ago @reggi!

For those who find their way here.... _.difference([0, 1, 3, 9], [1, 3]); // => [0, 9]

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

I know this is closed, but ES6's spread operator will help with this ;)

For anyone who doesn't want to search for ES6 spread operator that @agwidarsito mentioned, what he is saying is that you can do this in ES6:

const items = [1,2,3,4];
const itemsToRemove = [3,4,5];
const result = _.without(items, ...itemsToRemove);
// result is [1,2]

This issue was closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment