Approach 1 - Index and Splice (in-place)
Find the index
of the array element you want to remove using indexOf
, and then remove that index with splice
.
function removeItem(arr, item) {
let idx = arr.indexOf(item);
if (idx == -1) return;
arr.splice(idx, 1);
}
let arr = [1, 2, 3, 4, 5];
removeItem(arr);
console.log(arr);
// array = [1, 2, 4, 5]
It is important to check the value of the index. If there is no item in the array, then it will return -1.
Note that splice
modifies the array in place and returns a new array contraining the elements that have been removed.
array.splice(-1)
will remove the last element from the original array.
Approach 2 - Filter
Use the array method filter
. Note, that this will remove all elements that match the filter. It will return a copy though, leaving the original array intact.
let arr = [1,2,3,4,5];
let res = arr.filter(v => v !== 1);
console.log(arr);
// [1,2,3,4,5] Original array
console.log(res);
// [2,3,4,5] Filtered out array
Note that this method will remove all items that do not satisfy the filter. Therefore, in the example above, if there were multiple 1's in the original array, the array returned from filter will have all 1's removed.