boatcoder
boatcoder

Reputation: 18107

Is there a more concise way to remove an entry from an array with lodash?

Below are several stabs at removing 3 from the array [8,2,3,4] using lodash. The elegant syntax for removing an object from an array of objects makes me wonder if I just haven't figured out the right approach here.

> _.remove([8,2,3,4], 3)
  []
> x = [8,2,3,4]
  [8, 2, 3, 4]
> _.remove(x, 3)
  []
> x
  [8, 2, 3, 4]
> _.remove(x, {3: true})
  []
> x
  [8, 2, 3, 4]
> _.remove(x, [3])
  []
> x
  [8, 2, 3, 4]
> _.remove(x, function(val) { return val === 3; });
  [3]
> x
  [8, 2, 4]

Is there another way to remove a matching element from an array that would be similar to _.remove(arrayOfObjs, {id:3})

Upvotes: 0

Views: 51

Answers (1)

user229044
user229044

Reputation: 239301

Yes, but not using remove. You can instead use pull to remove values from an array:

Removes all provided values from array using SameValueZero for equality comparisons.

// pull modifies its argument:

x = [8, 2, 3, 4]
_.pull(x, 3)
x // => [8, 2, 4]

// pull also returns the modified array:

y = _.pull([1, 2, 3, 4, 5], 2, 3) //  => [1, 4, 5]

Upvotes: 3

Related Questions