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

时间:2015-03-14 15:18:28

标签: javascript lodash

以下是使用lodash从数组[8,2,3,4]中删除3的几次尝试。从对象数组中删除对象的优雅语法让我想知道我是否还没有找到正确的方法。

> _.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})

类似的匹配元素

1 个答案:

答案 0 :(得分: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]