有没有更简洁的方法可以从带有 lodash 的数组中删除条目

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

本文关键字:数组 lodash 删除 简洁 方法 有没有      更新时间:2023-09-26

下面是使用 lodash 从数组中删除 3 [8,2,3,4]的几个尝试。 从对象数组中删除对象的优雅语法让我怀疑我是否只是没有在这里找到正确的方法。

> _.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]

有没有另一种方法可以从类似于_.remove(arrayOfObjs, {id:3})的数组中删除匹配元素

是的,但不使用 remove .您可以改用pull从数组中删除值:

使用 SameValueZero 从数组中删除所有提供的值以进行相等比较。

// 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]