user6701863 user6701863 - 3 months ago 14
Javascript Question

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?

Answer

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