splice javascript

javascript splice method.

The splice() method of Array in javascript changes the content of an array, adding new elements while removing old elements.
If you specify a different number of elements to insert than the number you’re removing, the array will have a different length at the end of the call.

The Syntax is

array.splice(index , howMany[, element1[, ...[, elementN]]])

where

index : Index at which to start changing the array. If greater than the length of the array, no elements will be added or removed. If negative, will begin that many elements from the end.

howMany : An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If howMany is greater than the number of elements left in the array starting at index, then all of the elements through the end of the array will be deleted. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed.

element1, …, elementN : The elements to add to the array. If you don’t specify any elements, splice simply removes elements from the array.

This method returns an array containing the removed elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

Example Usages of .splice :-

1.To prepend an element at the start of an array.

Type this in your Devtools console

var array = [1,2,3,4] //We define the initial array
->undefined
array.splice(0,0,5) //index is 0, howmany is 0 and element is 5
->[]
array
->[5, 1, 2, 3, 4]
array.splice(0,0,6,7)//You can prepend n elements
->[6, 7, 5, 1, 2, 3, 4]

2.To remove the first element of an array.

To remove the first element from array ,

array.splice(0,1)

Type this in Devtools console :

array = [1,2,3,4]
->[1, 2, 3, 4]
array.splice(0,1)
->[1]
array
->[2, 3, 4]

Similarly to remove n elements from the start of an array :

array.splice(0,n)//n is no. of elems

3.Add and Remove elements from array

Let assume we want to add as well as remove elements from array at the same time
Consider code :
cities.splice(2,1,"Mumbai","Nagpur")

The index is 2 i.e. the 3rd element,
howmany is 1 ,i.e 1 element will be removed ,
“Mumbai”,”Nagpur” will get added at index 2.

Type this in console :-

var cities = ["Pune", "Bangalore", "Delhi", "Kolkata"]
->undefined
cities.splice(2,1,"Mumbai","Nagpur")
->["Delhi"]
cities
->["Pune", "Bangalore", "Mumbai", "Nagpur", "Kolkata"]

Sources

MDN splice

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>