Remove an item from an array in JavaScript
Learn how to remove an item from an array in JavaScript.
Removing a specific item from an array can be done a couple a few different ways. I'm going to show two ways for now using the filter method, and also a combination of the indexOf and splice methods.
Removing an item using the filter method
const value = 10;
const array = [3, 10, 15, 3, 20];
console.log(array); // [3, 10, 15, 3, 20]
const filteredArray = array.filter(item => {
return item !== value
});
console.log(filteredArray); // 3, 15, 3, 20
The filter method returns a new array with all items that pass the condition inside the function that's passed to it.
Remove an item using the indexOf method
Another way to remove an item from an array is to use the indexOf method.
const fruits = ['Apple', 'Orange', 'Grapes', 'Strawberries'];
const fruitToRemove = 'Orange';
console.log(fruits.indexOf(fruitToRemove)); // 1
indexOf should return the index of the value if it is found. If it isn't found, it will return -1.
We can now use this index to remove the item from the array.
const fruits = ['Apple', 'Orange', 'Grapes', 'Strawberries'];
const fruitToRemove = 'Orange';
const indexOfFruitToRemove = fruits.indexOf(fruitToRemove);
console.log(fruits); // ['Apple', 'Orange', 'Grapes', 'Strawberries']
if (indexOfFruitToRemove > -1) {
fruits.splice(indexOfFruitToRemove, 1);
};
console.log(fruits); // ['Apple', 'Grapes', 'Strawberries']
This basically:
- finds the fruit to remove in the array
- gives us the index of the Orange in the array
- then removes that single item from the array using the splice method