DEV Community

Discussion on: How to remove a specific item from an array

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Or just use filter to only remove the first match:

let myArr = [ "🍎", "🍏", "🍏", "🍍" ];
let removedArr = myArr.filter((r=>x=>r||!(r=x==="🍏"))())
console.log(removedArr);  // [ "🍎", "🍏", "🍍" ]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jcubic profile image
Jakub T. Jankiewicz • Edited

Interesting usage of closure to create blank variable name, but it's confusing as hell. I hope you don't write code like this, otherwise after a year you will spend few moments to figure out what the help is this.

It also doesn't make much sense to use filter for this case if it will iterate over every element even if it just nop. The reason why indexOf is used because it's faster if you want to remove first instance. If array have million items it your code will execute million times even if item is first on the list.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

I agree it doesn't make sense to use filter for this, I was just pointing out it was perfectly possible despite what the OP said.

Also, I love writing code like this - code that challenges and exercises the grey matter. It's like code poetry. Sometimes not the best plan in production though 😋