splice()
MethodYou can use the splice()
method to remove the item from an array at specific index in JavaScript. The syntax for removing array elements can be given with splice(startIndex, deleteCount)
.
Here, the startIndex
parameter specify the index at which to start splicing the array, it is required; the second parameter deleteCount
is the number of elements to remove (if it is set to 0 no element will be removed). Let's check out an example to understand 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>
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to reverse the order of an array in PHP
Use the PHP array_reverse() fu...How to create custom select box in HTML using CSS and jQuery
Use the CSS :selected Pseudo-class with...How to explode or split a string in JavaScript
Use the JavaScript split() method If...Use PHP Code into Laravel Blade
in this article, I will share with you h...How to Sort an Array of Integers Correctly in JavaScript
Use the sort() Method If you simply t...