To remove a specific item from an array in JavaScript, you can use the splice
method. The splice
method allows you to remove one or more elements from an array and insert new elements in their place, if desired.
Here is an example of how to use the splice
method to remove a specific item from an array:
let arr = [1, 2, 3, 4, 5];
// Remove the third element (index 2)
let removed = arr.splice(2, 1);
console.log(arr); // [1, 2, 4, 5]
console.log(removed); // [3]
The splice
method takes two arguments: the index of the first element to remove, and the number of elements to remove. In the example above, we remove one element at index 2 (the third element).
You can also use the splice
method to insert new elements into the array by passing additional arguments after the number of elements to remove. For example:
let arr = [1, 2, 3, 4, 5];
// Remove the third element (index 2) and insert a new element in its place
let removed = arr.splice(2, 1, 99);
console.log(arr); // [1, 2, 99, 4, 5]
console.log(removed); // [3]
Note that the splice
method modifies the original array and returns an array containing the removed elements. If you want to remove an element from an array without modifying the original array, you can use the filter
method.
let arr = [1, 2, 3, 4, 5];
let newArr = arr.filter(item => item !== 3);
console.log(arr); // [1, 2, 3, 4, 5]
console.log(newArr); // [1, 2, 4, 5]