How to remove specific element from an array in JavaScript
0 2330
You can easily remove the specific item (index) in JavaScript using the loop, and Array splice() Method. Array splice() method allows removing the item from an array at a specific index in JavaScript.
This method can be useful when you want to add/remove more than one element for a JavaScript Array.
Syntax:
array.splice(index, howmany, item1, ....., itemX)
Array splice() method requires 3 parameters.
- index: It is Required. It knows about specifies the position to remove/add (start splicing the array) the elements in the current JavaScript Array.
- howmany: It is an optional. It tells about how many specifies elements to be removed (deleteCount).
- item: It is Optional. It tells about how many specifies new elements to be added.
Program:
<!DOCTYPE html> <html> <head> <title> How to Remove specific index in JavaScript? </title> </head> <body> <h1>Remove an element from an array in JavaScript</h1> <p>The original array is: HTML, CSS, JavaScript, Jquery, PHP, MySQL</p> <p>Click the button to remove 3rd element from the array.</p> <p>The new array looks like this:<strong> <span id="display"></span> </strong></p> <br/> <button onclick="remove_ele()">Try it</button> <script type="text/javascript"> var WebLang = ["HTML", "CSS", "JavaScript", "Jquery", "PHP", "MySQL" ]; document.getElementById("display").innerHTML = WebLang; function remove_ele() { WebLang.splice(2, 1); document.getElementById("display").innerHTML = WebLang; } </script> </body> </html>
Share:
Comments
Waiting for your comments