14

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.

1
  • 2
    without lodash - a.filter( item => removeItem.indexOf( item.id ) == -1 ); Commented Jan 3, 2018 at 12:10

2 Answers 2

17

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
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.