How to Remove a specific Item from an Array in JavaScript
To remove a specific item from an array in JavaScript, you can use a combination of methods like indexOf()
and splice()
, or you can use the filter()
method.
1. Using indexOf()
and splice()
:
This method finds the index of the item in the array and then remove it by using splice()
.
let arr = [1,2,3,4,5];
let itemToRemove = 3;
let index = arr.indexOf(itemToRemove);
if(index !== -1) {
arr.splice(index, 1);
}
console.log(arr); //output: [1,2,4,5]
2. Using filter()
:
This method creates a new array with all elements that do not match the item you want to remove. It doesn’t modify the original array.
let arr = [1,2,3,4,5];
let itemToRemove = 3;
arr = arr.filter(item => item != itemToRemove);
console.log(arr); // Output: [1,2,4,5]
splice()
modifies the original array, whereas filter()
returns a new array.indexOf()
returns -1
if the item is not found, so it’s important to check for this before calling splice()
.