Dan Zaner
Dan Zaner

Reputation: 169

Using Underscore (or Lodash), how do you remove every member of an array from another array?

I'm trying to use Underscore ( or Lodash) to remove every member of one array from another. For example, if I have the array

[1, 5, 2] 

how do you efficiently remove every instance of every member of that array from some other array, such as:

[1, 1, 7, 2, 3, 6, 3, 4, 5, 6, 6, 7, 8]

I'm expecting to get:

[7, 3, 6, 3, 4, 6, 6, 7, 8] 

as the result. All my attempts with _.without() have failed, but I have a sneaking suspicion I'm just not calling it correctly.

Thanks in advance for the help!

Upvotes: 1

Views: 210

Answers (2)

epascarello
epascarello

Reputation: 207521

Look at difference

var a = [1, 1, 7, 2, 3, 6, 3, 4, 5, 6, 6, 7, 8];
var b = [1, 5, 2];

console.log(_.difference(a,b));

Upvotes: 1

Anthony Chu
Anthony Chu

Reputation: 37520

Try _.difference()...

Returns the values from array that are not present in the other arrays.

_.difference([1, 1, 7, 2, 3, 6, 3, 4, 5, 6, 6, 7, 8], [1, 5, 2]);

Demo - JSFiddle

Upvotes: 2

Related Questions