[英]How do I remove just one element from my array based on its value if there are more than one of each value
如果每个值有多个,如何根据值从数组中仅删除一个元素。 顺便说一句,该数组是一副纸牌。
如果您不知道它在数组中的位置,您可以使用findIndex
:
const index = theArray.findIndex(entry => entry.property === value);
这将返回第一个匹配项的索引,如果未找到匹配项,则返回 -1。 然后您可以通过使用splice
修改原始数组来删除它:
theArray.splice(index, 1);
...或通过创建一个省略该元素的新数组:
theArray = theArray.filter((e, i) => i !== index);
现场示例:
let theArray = [ {suit: "Diamonds", number: 1}, {suit: "Clubs", number: 7}, {suit: "Spades", number: 6}, {suit: "Clubs", number: 1} ]; // Find and remove the first Club const index = theArray.findIndex(entry => entry.suit === "Clubs"); if (index !== -1) { theArray.splice(index, 1); console.log("Updated array:", theArray); } else { console.log("Not found"); }
.as-console-wrapper { max-height: 100% !important; }
另一种方法是只使用filter
来创建一个新数组,用一个标志告诉自己是否已经找到并删除了该项目:
let found = false;
theArray = theArray.filter(entry => found || !(found = entry.property === value));
现场示例:
let theArray = [ {suit: "Diamonds", number: 1}, {suit: "Clubs", number: 7}, {suit: "Spades", number: 6}, {suit: "Clubs", number: 1} ]; // Find and remove the first Club let found = false; theArray = theArray.filter(entry => found || !(found = entry.suit === "Clubs")); console.log("Updated array:", theArray);
.as-console-wrapper { max-height: 100% !important; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.