简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM