This article explains how to remove elements from a JavaScript array.
In the following example, we define a custom method for deleting array elements:
Example
Array.prototype.removeByValue = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
var sites = ['apple', 'google', 'example', 'taobao'];
sites.removeByValue('google');
console.log(sites);
// -> ['apple', 'example', 'taobao']
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
var sites = ['apple', 'google', 'example', 'taobao'];
sites.removeByValue('google');
console.log(sites);
// -> ['apple', 'example', 'taobao']
Try it Yourself »
You can also usearray.spliceMethod to implement:
Example
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1); // The second parameter is the number of deletions; set to delete only once
}
// array = [2, 9]
console.log(array);
console.log(array);
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1); // The second parameter is the number of deletions; set to delete only once
}
// array = [2, 9]
console.log(array);
Try it Yourself »
The following example sets up the ability to delete one or more elements from an array:
Example
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;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
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;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
Try it Yourself »