How to remove an element from an array in JavaScript?
Array splice() method can be used to remove any particular element from an array in JavaScript. Moreover, this function can be used to add/remove more than one element from an array.
Syntax:
array.splice(index, howmany, item1, ....., itemX)
Parameters: This method requires 3 parameters :-
- index: Required. It specifies the position to remove/add the elements.
- howmany: Optional. It specifies how many elements to be removed.
- item: Optional. It specifies new elements to be added.
Return Value: A new Array, containing the removed items (if any).
Example: This example uses splice() method to remove particular element from an array.
<!DOCTYPE html> < html > < body > < h1 >Welcome to GeeksforGeeks</ h1 > < p >Click the button to remove 3rd element from the array.</ p > < button onclick = "remove_ele()" >Try it</ button > < p id = "display" ></ p > < p id = "demo" ></ p > <!--Script to remove an element from an array using spice method--> < script > var Lang = ["C++ ", " Java ", " Python ", " Go ", " Prolog"]; document.getElementById("display").innerHTML = Lang; function remove_ele() { Lang.splice(2, 1); document.getElementById("display").innerHTML = Lang; } </ script > </ body > </ html > |
Output:
Before clicking try it button:
After clicking try it button:
Supported Browsers: The browser supported by Array splice() Method are listed below:
- Google Chrome
- Apple Safari
- Firefox
- Opera
- Edge