Answer: Use the splice()
Method
You can use the splice()
method to remove the item from an array at a specific index in JavaScript. For example, you can remove array elements using splice(startIndex, deleteCount)
.
The startIndex
parameter specifies the index at which to begin splicing an array. It is mandatory. The deleteCount
parameter is the number of elements to be deleted. If it is set to 0, no element will ever be removed. Let’s look at an example to see how it works.
<script>
var colors = ["Red", "Green", "Blue", "Yellow", "Orange"];
var removed = colors.splice(2,1); // Removes the third element
console.log(colors); // Prints: ["Red", "Green", "Yellow", "Orange"]
console.log(removed); // Prints: ["Blue"] (one item array)
console.log(removed.length); // Prints: 1
var persons = ["Alice", "John", "Peter", "Clark", "Harry"];
removed = persons.splice(2,2); // Removes the third and fourth elements
console.log(persons); // Prints: ["Alice", "John", "Harry"]
console.log(removed); // Prints: ["Peter", "Clark"]
console.log(removed.length); // Prints: 2
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
removed = fruits.splice(2); // Removes all elements starting at index 2
console.log(fruits); // Prints: ["Apple", "Banana"]
console.log(removed); // Prints: ["Mango", "Orange", "Papaya"]
console.log(removed.length); // Prints: 3
</script>
Important to remember that the splice()
function modifies the original array it is called upon and returns either a new array with the deleted elements, or an empty array if none were deleted.
You can also remove all elements starting at the beginning and ending of an array if you omit the second argument, which is deleteCount
) , as shown in the example above.
Leave a Reply