In this article, you will learn how to remove a specific item from an array in JavaScript in the easiest way.
Contents
In JavaScript, you can remove a specific item from an array by using the splice()
method. The splice()
method changes the content of an array by removing or replacing elements.
The syntax for splice()
method is as follows:
array.splice(index, count, item1, item2, ...)
The first parameter of the splice()
method specifies the index of the array where you want to start removing elements. The second parameter specifies the number of elements to remove.
Remove a specific item from an Array
For example, to remove the element at index 2 from the following array:
let array = ["apple", "banana", "orange", "pineapple"];
You can use the splice()
method as follows:
let removedItem = array.splice(2, 1);
The splice()
method will remove the element at index 2 (“orange”) from the array
and return a new array that contains the removed element. In this case, removedItem
will contain the value “orange”.
If you want to remove multiple elements from the array, you can specify the number of elements to remove as the second parameter of the splice()
method. For example:
let removedItems = array.splice(1, 2);
This will remove two elements starting at index 1 (“banana” and “orange”) and return a new array that contains the removed elements.
Insert new elements at a specific index of an Array
If you don’t want to remove any elements from the array, but want to insert new elements at a specific index, you can specify the number of elements to remove as 0 and pass the new elements as additional parameters. For example:
array.splice(2, 0, "grape", "pear");
This will insert the elements “grape” and “pear” at index 2 of the array
without removing any elements.
In summary, the splice()
method in JavaScript can be used to remove a specific item from an array by specifying the index and count of elements to remove. It can also be used to insert new elements at a specific index of the array.
Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.