MonkeyBonkey
MonkeyBonkey

Reputation: 47881

how to use lodash _ without operator with an array rather than multiple args

I was expecting the lodash without function to take an array of values, but instead takes multiple args. How do I pass it an array and make it work.

Example:

var bar = {
    foo: ['a', 'b', 'c']
};


_.without(bar.foo, 'c', 'a'); // works;
_.without(bar.foo, ['c', 'a']); // doesn't work

My exclusion list has to be passed in as an array or variable so it would be useful to know how to use an array with the without function.

Upvotes: 12

Views: 4720

Answers (4)

user3462064
user3462064

Reputation: 515

Could use spread operator

var bar = {
    foo: ['a', 'b', 'c']
};

var arr = ['c', 'a'];

console.log(_.without([bar.foo], ...arr) ;

Upvotes: 1

user663031
user663031

Reputation:

If you're in an environment where you can use the ES6 spread operator, ..., then

.without(bar.foo, ...['c', 'a']);

Upvotes: 13

thefourtheye
thefourtheye

Reputation: 239483

In this case, you can use the array of values as it is, with _.difference, like this

console.log(_.difference(bar.foo, ['a', 'c']));
[ 'b' ]

Upvotes: 13

Oleksandr T.
Oleksandr T.

Reputation: 77482

You can use .apply

var bar = {
    foo: ['a', 'b', 'c']
};


console.log(_.without.apply(_, [bar.foo].concat(['c', 'a'])));
<script src="https://rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script>

Upvotes: 4

Related Questions