To remove a specific item from an array in JavaScript, you can use the splice()
method. The splice()
method changes the content of an array by removing or replacing existing elements and/or adding new elements.
Here is an example code snippet that removes an element from an array by its index:
const array = [1, 2, 3, 4, 5]; const indexToRemove = 2; // remove the third element (index 2) array.splice(indexToRemove, 1); console.log(array); // [1, 2, 4, 5]
In the example above, the splice()
method is called on the array
variable with the index of the element to remove and the number of elements to remove. In this case, only one element is removed.
If you want to remove an element from an array by its value, you can use the indexOf()
method to find its index first:
const array = ['apple', 'banana', 'orange', 'peach'];
const valueToRemove = 'orange';
const indexToRemove = array.indexOf(valueToRemove);
if (indexToRemove !== -1) {
array.splice(indexToRemove, 1);
}
console.log(array); // ['apple', 'banana', 'peach']
In the example above, the indexOf()
method is used to find the index of the valueToRemove
in the array
. If the valueToRemove
is found, the splice()
method is called with the indexToRemove
and the number of elements to remove (which is 1 in this case).
Using ECMA6
const value = 3 let arr = [1, 2, 3, 4, 5, 3] let = arr.filter(function(item) { return item !== value }) console.log(arr) // [ 1, 2, 4, 5 ]