Remove Items From An Array In Javascript
A handy reference for removing specific items from your array
When you know the index
If we know the index of the item we want to remove we can perform a simple splice
function removeAtIndex(arr, idx) {
arr.splice(idx, 1);
}
let nums = [1,2,3,4];
removeAtIndex(nums, 2);
// nums = [1,2,4]
Explanation: .splice
is an array method which takes at least one argument. The first/required argument is the index of the item to remove. The second is the number of items to remove. in this case, we just want to remove the item at that index so we write 1
. Spice will alter the original array so we don't need to return anything.
When we want to replace the value
We can still use spice we just need to add another argument
function replaceAtIndex(arr, idx, replacement) {
arr.splice(idx, 1, replacement);
}
let nums = [1,2,3,4];
replaceAtIndex(nums, 2, 5);
// nums = [1,2,5,4]
Explanation: .splice
can take more arguments, each additional argument will be inserted in the array at the position stated in the first argument
When you know the value
If we know the value we want to remove from an array we can find the index and use the same technique as above.
function removeValue(arr, val) {
const idx = arr.indexOf(val);
arr.splice(idx, 1);
}
let nums = [1,2,3,4];
removeValue(nums, 3);
// nums = [1,2,4]
Explanation: .indexOf
will take a value and tell us the position of the first element with that value. note: if more than one element has the same value this will only return the index of the first one
When you want to remove multiple items
If we want to remove multiple items with the same value we will need to loop through the whole array at least once. So in this instance, it would be effective to use .filter
function removeAll(arr, val) {
return arr.filter(v => v !== val)
}
const nums = [1,2,3,4,1,2,3,4];
const filteredNums = removeAll(nums, 3);
// filteredNums = [1,2,4,1,2,4]
Explanation: .filter
has a single callback function as an argument. That function should return true if we want to keep it in the array and false if we want to remove it. So we use the !==
operator to return false if any value is the same as val
. note: filter returns the new array and does not affect the original array
When you have multiple values you want to remove
Maybe there is an array of possible values you want to remove? Then you can use includes
:
function removeAllVaues(arr, vals) {
return arr.filter(v => !vals.includes(v))
}
const nums = [1,2,3,4,1,2,3,4];
const filteredNums = removeAllVaues(nums, [2,3]);
// filteredNums = [1,4,1,4]
Explanation: The .includes()
method accepts a single value as argument and will return true if that value is in the array