Estimated reading time: 2 minutes
Removing specific items from an array in JavaScript is a common task, yet JavaScript doesn’t offer a simple .remove() method. This guide covers multiple ways to remove items using core JavaScript functions like splice and filter. We’/sepll also include code snippets and examples to help you choose the best approach for your use case.
TL;DR
To remove a specific item from an array in JavaScript:
- Use
splicefor index-based removal. - Use
filterfor functional removal based on values.
Removing an Item by Index with splice
The splice method is ideal if you know the index of the item you want to remove.
Syntax
array.splice(index, 1);
Here, index is the position of the item, and 1 specifies that only one item should be removed.
Example:
To remove 5 from an array:
const array = [2, 5, 9];
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1);
}
console.log(array); // Output: [2, 9]
Note: splice modifies the original array.
Wrapping it in a function
For situations where you want to remove only the first occurrence of a specific value, you can wrap splice in a function.
Example:
function removeItemOneOccurance(arr, value) {
const index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
console.log(removeItemOneOccurance([2, 5, 9, 5], 5)); // Output: [2, 9, 5]
Removing All Occurrences by Value
To remove all instances of a specific value, use a loop that checks for the value at each index.
Example:
function removeItemAllOccurance(arr, value) {
let i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
i++;
}
}
return arr;
}
console.log(removeItemAllOccurance([2, 5, 9, 5, 5], 5)); // Output: [2, 9]
Functional Approach with filter
If you prefer a functional approach that doesn’t modify the original array, use filter.
Example:
const array = [2, 5, 9, 5];
const newArray = array.filter(item => item !== 5);
console.log(newArray); // Output: [2, 9]
This method creates a new array excluding the specified value, making it useful in functional programming contexts.
Additional Tips
- Avoid
delete: Usingdeleteon array elements only removes the value but leaves an empty slot, causing unexpected behavior. - Use
indexOffor Checking: Always check for the presence of an item before usingsplice, asindexOfreturns-1if the item is not found.
Reference Links
- Stack Overflow: How can I remove a specific item from an array in JavaScript?
- MDN Web Docs: Array.prototype.splice()
- MDN Web Docs: Array.prototype.filter()
- MDN Web Docs: Array.prototype.indexOf()
