过滤和删除数组中的过滤元素

新手上路,请多包涵

我想删除原始数组中的特定元素(即 var a )。我 filter() 那个数组和 splice() 返回了新数组。但这并不影响这段代码中的原始数组。如何轻松地从原始数组中删除这些元素?

 var a = [{name:'tc_001'}, {name:'tc_002'}, {name:'tc_003'}]

var b = a.filter(function (e) {
    return e.name === 'tc_001';
});

b.splice(0,1);

console.log(a);
console.log(b);

原文由 s1n7ax 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 604
2 个回答

Array.prototype.filter() 方法用于收集一个元素集而不是只有一个项目。如果您想通过评估条件获得一件物品,那么您还有其他三种选择:

  • Array.prototype.indexOf()
  • Array.prototype.findIndex()
  • Array.prototype.find()

因此,只有当您想对多个项目进行操作时,您才应该考虑使用过滤器功能。就需要完成的工作而言,没有一个答案是完整的。

他们使用过滤功能来隔离一组(在这个例子中恰好只是一个项目)但他们没有展示如何摆脱整个集合。好吧,让我们澄清一下。

如果你只想查找和删除数组中的一项,那么应该这样做

 var a = [{name:'tc_001'}, {name:'tc_002'}, {name:'tc_003'}];
a.splice(a.findIndex(e => e.name === "tc_001"),1);
console.log(a);

但是,由于您以复数形式提到“特定元素”,因此您需要收集一组选定的项目,并对集合中的每个元素一个接一个地执行上述工作。所以正确的方法是。

 var a = [{name:'tc_001'}, {name:'tc_002'}, {name:'tc_003'}],
    b = a.filter(e => e.name === "tc_001");
b.forEach(f => a.splice(a.findIndex(e => e.name === f.name),1));
console.log(a);

无论您选择的列表中有多少元素,这都可以完成您的工作。然而我相信,尽管这看起来合乎逻辑,但它做了很多多余的工作。首先过滤,然后每个过滤的元素做索引搜索这个那个。尽管我知道 findIndex 的速度非常快,但我还是希望这个会明显变慢,尤其是对于大数组。让我们找到一个 O(n) 的解决方案。干得好:

 var a = [{name:'tc_001'}, {name:'tc_002'}, {name:'tc_003'}];
a = a.reduce((p,c) => (c.name !== "tc_001" && p.push(c),p),[]);
console.log(a);

所以这一定是它。

原文由 Redu 发布,翻译遵循 CC BY-SA 4.0 许可协议

另一种方法是像这样过滤两个列表:

 const originalList = [{condition:true}, {condition: false}, {condition: true}];

// wished lists
const listWithTrue = originalList.filter(x=>x.condition);
const listWithFalse = originalList.filter(x=>!x.condition); // inverse condition

原文由 Ninja Coding 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题