Remove Specific Elements from JavaScript Arrays
There are many ways to remove specific items from an array in JavaScript, but one of the easiest methods is to use the filter()
function.
Here’s a quick guide, including examples for single and multiple-item removal.
Single Item Removal
To remove a single item from an array, you can use the filter()
method to create a new array that contains all elements of the original array except for the specified item to remove.
const array = [1, 2, 3, 4, 5]; const itemToRemove = 3; const filteredArray = array.filter(item => item !== itemToRemove); console.log(filteredArray); // [1, 2, 4, 5]
In this example, filter()
iterates over the array and returns a new array that includes every item except for the one that matches itemToRemove
.
Multiple Items Removal
To remove multiple items from an array, you can still use the filter()
method, but this time, we also use the includes()
method. This allows you to specify an array of items to remove.
const array = [1, 2, 3, 4, 5]; const itemsToRemove = [2, 4]; const filteredArray = array.filter(item => !itemsToRemove.includes(item)); console.log(filteredArray); // [1, 3, 5]
Here, filter()
is used to iterate over the array, and for each element, includes()
checks if it is in the itemsToRemove
array. If an item is not included in itemsToRemove
, it's kept in the resulting filteredArray
.