DevTips Daily: How to remove a specific item from an array in JavaScript

preview_player
Показать описание
⭐️ Check out more DevTips Daily ⭐️

#devtipsdaily Channel Handle @codebubb
Рекомендации по теме
Комментарии
Автор

Great stuff, James! Showing multiple ways to handle tasks is really helpful.

My rookie approach: Sometimes I use the delete operator, which will delete the element but leave an empty element in its place (I like to think of it as a placeholder in case I need to keep the index numbers):

delete array[array.indexOf(4)]
//... do some stuff to the array and then remove the empty elements with


let newArray = array.filter(n => n != null);

krisw.
Автор

awesome content :) I just couldn't help myself and I had to subscribe :)
For array.splice() method. I had some headache with this one day, when instead of removing object I hoped would be removed, suddenly some random stuff started to vanish. I've noticed it's always last object from array was missing and then I got this idea to actually read about splice method... and yes. when you try to establish index of item to remove, and this item is already gone, you get -1 and what it does with splice? it removes last object. As I remember -2 would remove second last and so on. So yes. When I've figured filtering method for removing stuff from arrays I've never looked back. :)

swojchwat
Автор

or use the "continue" key word

let nums = [1, 2, 3, 4, 5, 6]

let arr = []

for (let num of nums) {
if (num === 4) continue
else arr.push(num + 2)
}

console.log(arr) // [3, 4, 5, 7, 8]

juancamacho
Автор

Thank you. That was some fast speech, though. But appreciate.

MS-gihc