Remove a specific item from an array in JavaScript.
How can I remove a specific item from an array in JavaScript?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
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
forloopThe
forloop can be used to iterate through the array and remove the item you want to remove.The
forloop takes three arguments:For example, the following code removes the item with the value
2from the arraymyArray:Method 3: Using the
whileloopThe
whileloop can be used to iterate through the array and remove the item you want to remove.The
whileloop takes two arguments:For example, the following code removes the item with the value
2from the arraymyArray: