JavaScript(JS) JS remove specific item from an array
To remove a specific item from an array using JavaScript, you can use the splice()
method. The splice()
method modifies the array by removing or replacing existing elements and returning an array of the removed elements.
Here's an example code that removes a specific item from an array:
let arr = [1, 2, 3, 4, 5]; let itemToRemove = 3; let index = arr.indexOf(itemToRemove); if (index !== -1) { arr.splice(index, 1); } console.log(arr); // Output: [1, 2, 4, 5]
In this code, we define an array called arr
and a variable called itemToRemove
that represents the value to remove from the array. We use the indexOf()
method to find the index of the item in the array, and then check if it's not -1
(i.e., the item was found in the array).
If the item is found, we use the splice()
method to remove it from the array. The splice()
method takes two arguments: the starting index of the splice operation (in our case, the index of the item to remove), and the number of elements to remove (in our case, 1).
Finally, we print the modified array to the console using console.log()
.
Note that this code only removes the first occurrence of the item in the array. If you want to remove all occurrences of the item, you can use a loop to repeat the splice()
operation until the item is no longer found in the array.