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

I am looking at 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 to remove friend_id: 14friends from an array?

+4
source share
2 answers

You can use a 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; });
+3
source

Remove uses a predicate function. 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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>
Run codeHide result
+2
source

Source: https://habr.com/ru/post/1651969/


All Articles