Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 735
Gitesh Purbia Avatar asked Jan 03 '18 12:01

Gitesh Purbia


People also ask

How do I remove an object from an array by id?

To remove an element from an array by ID in JavaScript, use the findIndex() method to find the index of the object with the ID in the array. Then call the splice() method on the array, passing this index and 1 as arguments to remove the object from the array.

How do I remove from an array those elements that exists in another array?

To remove elements contained in another array, we can use a combination of the array filter() method and the Set() constructor function in JavaScript.


1 Answers

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
like image 120
Gabriele Petrioli Avatar answered Sep 27 '22 19:09

Gabriele Petrioli