How to Delete an Item from a List in JavaScript?

Estimated read time 1 min read

In JavaScript, you can delete an item from a list using the splice() method. The splice() method allows you to modify an array by adding or removing elements.

To remove an item from a list, you can use the indexOf() method to find the index of the item in the list and then use the splice() method to remove it.

Here’s an example code snippet:

let myList = ["item 1", "item 2", "item 3", "item 4"];

let index = myList.indexOf("item 2");

if (index !== -1) {
  myList.splice(index, 1);
}

console.log(myList);

In the above code, the indexOf() method is used to find the index of the item “item 2”. If the item is found, the splice() method is used to remove the item from the list.

The first argument of the splice() method is the index at which to start changing the array, and the second argument is the number of elements to remove. In this case, we are removing only one element at the given index.

Note that the splice() method modifies the original array, so make sure to use it carefully.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply