Removing a specific item from an array in JavaScript is something almost every developer needs to do — and thankfully, JavaScript gives you a few handy ways to do it, depending on the situation.
Let’s say you have an array like this:
let fruits = ['apple', 'banana', 'orange', 'banana'];
And you want to remove 'banana'. Here are a few ways you can go about it:
indexOf() + splice()
This combo is great when you want to remove the first occurrence of an item.
let index = fruits.indexOf('banana');
if (index > -1) {
fruits.splice(index, 1);
}
filter() – To remove all instances of an item:
fruits = fruits.filter(fruit => fruit !== 'banana');
This is super clean and removes every 'banana' from the array.
splice() – If you know the index:
If you know the position, like index 1:
fruits.splice(1, 1); // removes one item at index 1
A Few Tips:
- splice() modifies the original array.
- filter() returns a new array — good for functional programming styles.
- Be careful with delete — it removes the value but leaves an empty slot (not ideal).
So yeah, depending on whether you want to remove one item or all of them, JavaScript gives you flexible tools to do the job