简体   繁体   中英

How do I remove just one element from my array based on its value if there are more than one of each value

How do I remove just one element from an array based on value if there are multiples of each value. The array is a deck of cards btw.

If you don't know where it is in the array, you can find out using findIndex :

const index = theArray.findIndex(entry => entry.property === value);

That returns the index of the first match, or -1 if no match was found. Then you can remove it either by using splice to modify the original array:

theArray.splice(index, 1);

...or by creating a new array omitting that element:

theArray = theArray.filter((e, i) => i !== index);

Live Example:

 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; }

Another approach is to just use filter to create a new array, with a flag telling yourself whether you've already found and removed the item:

let found = false;
theArray = theArray.filter(entry => found || !(found = entry.property === value));

Live Example:

 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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM