Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash remove to remove an object from the array based on an id property

I am looking at the lodash documentation for remove() and I am not sure how to use it.

Say I have an array of Friends,

[{ friend_id: 3, friend_name: 'Jim' }, { friend_id: 14, friend_name: 'Selma' }]

How do you remove friend_id: 14 from the array of Friends?

like image 870
user6701863 Avatar asked Aug 21 '16 23:08

user6701863


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 you remove an object from an array from a property?

To remove an object from an array by its value:Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.

How do I remove an object from an array of objects?

Use array. map() method to traverse every object of the array. For each object use delete obj. property to delete the certain object from array of objects.

How do I remove an object with Lodash?

remove() Method. The _. remove() method is used to remove all elements from the array that predicate returns True and returns the removed elements.


2 Answers

Remove uses a predicate function. See example:

var friends = [{ friend_id: 3, friend_name: 'Jim' }, { friend_id: 14, friend_name: 'Selma' }];

_.remove(friends, friend => friend.friend_id === 14);

console.log(friends); // prints [{"friend_id":3,"friend_name":"Jim"}]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>
like image 177
Tamas Hegedus Avatar answered Oct 21 '22 00:10

Tamas Hegedus


You can use filter.

var myArray = [1, 2, 3];

var oneAndThree = _.filter(myArray, function(x) { return x !== 2; });

console.log(allButThisOne); // Should contain 1 and 3.

Edited: For your specific code, use this:

friends = _.filter(friends, function (f) { return f.friend_id !== 14; });
like image 31
Scottie Avatar answered Oct 21 '22 00:10

Scottie