Given an array, the task is to remove an item from an array by value in JavaScript. While arrays in JavaScript provide methods to remove items by index, removing by value requires slightly more effort. This article will cover all the ways to remove an item from an array by value, explaining its syntax, pros, cons, and use cases.
1. Using Array filter() Method
The filter()
method creates a new array with all elements that pass a specified condition. To remove an item by value, you can filter out the elements that match the value.
let arr = [10, 20, 30, 40, 50]; let removeValue = 30; let filteredArr = arr.filter(item => item !== removeValue); console.log(filteredArr); // Output: [10, 20, 40, 50]
2. Using Array splice() Method
The splice()
method modifies the original array by adding, removing, or replacing elements. To remove an item by value, you first need to find its index using indexOf()
.
let arr = [10, 20, 30, 40, 50]; let removeValue = 30; let index = arr.indexOf(removeValue); if (index !== -1) { arr.splice(index, 1); } console.log(arr); // Output: [10, 20, 40, 50]
3. Using Array findIndex() with splice() Method
If you need to remove an item based on a condition, findIndex()
can be used to locate the index of the element, followed by splice()
to remove it.
let arr = [10, 20, 30, 40, 50]; let removeValue = 30; let index = arr.findIndex(item => item === removeValue); if (index !== -1) { arr.splice(index, 1); } console.log(arr); // Output: [10, 20, 40, 50]
4. Using Array reduce() Method
The reduce()
method can be used to build a new array while excluding the value to remove.
let arr = [10, 20, 30, 40, 50]; let removeValue = 30; let reducedArray = arr.reduce((acc, item) => { if (item !== removeValue) { acc.push(item); } return acc; }, []); console.log(reducedArray); // Output: [10, 20, 40, 50]
5. Removing All Occurrences of a Value
If the array contains duplicate values and you want to remove all occurrences, filter()
is the most straightforward method.
let arr = [10, 20, 30, 40, 30, 50]; let removeValue = 30; let filteredArray = arr.filter(item => item !== removeValue); console.log(filteredArray); // Output: [10, 20, 40, 50]
6. Using a Loop for Manual Removal
In older JavaScript environments or for more manual control, you can use loops to remove items.
let arr = [10, 20, 30, 40, 50]; let removeValue = 30; for (let i = 0; i < arr.length; i++) { if (arr[i] === removeValue) { arr.splice(i, 1); i--; } } console.log(arr); // Output: [10, 20, 40, 50]