JavaScript Array splice() method : The splice() method is used to add or remove the element from/to array. Using the parameter we can add or remove element to/from desired position. It changes the original array. The splice() method returns the removed item.
Syntax of array splice() method :
array.splice(index, howmany, element1,.....,elementX)
index : Required. This numeric value defines that in which position item should be add/remove. To count from last position use negative value.
howmany : Required. This numeric value defines that how many items need to remove from the array.
element1..elementX : Optional. These are the new elements need to add to the array.
Example of Array splice() method : In the following example I will show you how to add and remove the item in the array.
In Sample1.html I will show how to remove the elements of array from given position.
Sample1.html
<!DOCTYPE html>
<html>
<body>
<p>To remove the two elements from the array, click the button "remove".</p>
<button onclick="removeElements()">remove</button>
<p id="container"></p>
<script>
function removeElements() {
var students = ["Ashok", "Nitin Kumar", "Rajesh", "Pankaj", "Sumit", "Manish", "Pramod"];
students.splice(1, 2);
document.getElementById("container").innerHTML = students;
}
</script>
</body>
</html>
Output :
Ashok,Pankaj,Sumit,Manish,Pramod
In Sample2.html I will show how to add new elements in array at desired position without removing any element.
Sample2.html
<!DOCTYPE html>
<html>
<body>
<p>To add the two elements at position 2 in the array without removing any element, click the button "add items".</p>
<button onclick="addElements()">add items</button>
<p id="container"></p>
<script>
function addElements() {
var students = ["Ashok", "Nitin Kumar", "Rajesh", "Pankaj", "Sumit", "Manish", "Pramod"];
students.splice(2, 0, "Prince", "Logan");
document.getElementById("container").innerHTML = students;
}
</script>
</body>
</html>
Output :
Ashok, Nitin Kumar, Prince, Logan, Rajesh, Pankaj, Sumit, Manish, Pramod
In Sample3.html I will show how to do both add and remove operations together in array.
Sample3.html
<!DOCTYPE html>
<html>
<body>
<p>To add the two elements at position 1 in the array and also removing three elements, click the button "add items".</p>
<button onclick="addElements()">add items</button>
<p id="container"></p>
<script>
function addElements() {
var students = ["Ashok", "Nitin Kumar", "Rajesh", "Pankaj", "Sumit", "Manish", "Pramod"];
students.splice(1, 3, "Prince", "Logan");
document.getElementById("container").innerHTML = students;
}
</script>
</body>
</html>
Output :
Ashok, Prince, Logan, Sumit, Manish, Pramod
0 Comment(s)