简体   繁体   中英

Lodash Remove objects from array by matching ids array

I have an array of objects like:

var a = [
  {id: 1, name: 'A'},
  {id: 2, name: 'B'},
  {id: 3,  name: 'C'},
  {id: 4, name: 'D'}
];

And Ids array which i want to remove from array a :

var removeItem = [1,2];

I want to remove objects from array a by matching its ids, which removeItem array contains. How can i implement with lodash.

I Checked lodash's _.remove method, but this need a specific condition to remove an item from array. But i have list of ids which i want to remove.

As you mentioned you need the _.remove method and the specific condition you mention is whether the removeItem array contains the id of the checked element of the array.

var removeElements = _.remove(a, obj => removeItem.includes(obj.id));
// you only need to assign the result if you want to do something with the removed elements.
// the a variable now holds the remaining array

You have to pass a predicate function to .remove method from lodash .

var final = _.remove(a, obj => removeItem.indexOf(obj.id) > -1);

using indexOf method.

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

You can do it using native javascript using filter method which accepts as parameter a callback function.

 var a = [ {id: 1, name: 'A'}, {id: 2, name: 'B'}, {id: 3, name: 'C'}, {id: 4, name: 'D'} ]; var removeItem = [1,2]; a = a.filter(function(item){ return removeItem.indexOf( item.id ) == -1; }); console.log(a); 

But filter method just creates a new array by applying a callback function.

From documentation :

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

If you want to modify the original array use splice method.

 var a = [ {id: 1, name: 'A'}, {id: 2, name: 'B'}, {id: 3, name: 'C'}, {id: 4, name: 'D'} ]; var removeItem = [1,2]; removeItem.forEach(function(id){ var itemIndex = a.findIndex(i => i.id == id); a.splice(itemIndex,1); }); console.log(a); 

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