Asked by Sohail · · 2 answers
Find the index of the array element you need to delete using indexOf
, and afterward delete that index with splice
.
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1);
}
// array = [2, 9]
console.log(array);
The second parameter of splice is the number of elements to eliminate. Note that splice changes the array in place and returns a new array containing the elements that have been removed.
Function removes only a single occurrence:
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
//Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
Function removes all occurrences:
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
//Usage
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
1
0