js remove an element from array, if an element is code example
Example 1: remove element from array javascript
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
console.log(removeItemOnce([2, 5, 9, 1, 5, 8, 5], 5));
console.log(removeItemAll([2, 5, 9, 1, 5, 8, 5], 5));
Example 2: how to remove element from array in javascript
let numbers = [1, 2, 3, 4, 5];
numbers.pop();
numbers.shift();
let threeIndex = numbers.indexOf(3);
numbers.splice(threeIndex, 1);
numbers.splice(threeIndex, 1, 7)