How can I remove a specific item from an array in JavaScript?
Remove a specific item from an array in JavaScript.
18420-Jul-2023
Updated on 21-Jul-2023
Home / DeveloperSection / Forums / Remove a specific item from an array in JavaScript.
How can I remove a specific item from an array in JavaScript?
Aryan Kumar
21-Jul-2023There are a few ways to remove a specific item from an array in JavaScript.
Method 1: Using the
indexOf()
methodThe
indexOf()
method can be used to find the index of an item in an array. Once you have the index of the item you want to remove, you can use thesplice()
method to remove it from the array.The
splice()
method takes three arguments:For example, the following code removes the item with the index 1 from the array
myArray
:Method 2: Using the
for
loopThe
for
loop can be used to iterate through the array and remove the item you want to remove.The
for
loop takes three arguments:For example, the following code removes the item with the value
2
from the arraymyArray
:Method 3: Using the
while
loopThe
while
loop can be used to iterate through the array and remove the item you want to remove.The
while
loop takes two arguments:For example, the following code removes the item with the value
2
from the arraymyArray
: