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?
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.
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.
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.
remove() Method. The _. remove() method is used to remove all elements from the array that predicate returns True and returns the removed elements.
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>
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With