user6701863
user6701863

Reputation: 147

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?

Upvotes: 8

Views: 20430

Answers (3)

Tamas Hegedus
Tamas Hegedus

Reputation: 29926

Remove expects a predicate function. See this 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>

Upvotes: 24

gk.
gk.

Reputation: 358

You can also do it like this

list.splice(_.findKey(this.list, function(e) {
    return e.id === 12;
}), 1);

Upvotes: 0

Scottie
Scottie

Reputation: 11308

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

Upvotes: 10

Related Questions