splice() - Push or pop to array at position


splice() - Add or remove elements to array at position

I have been trying to push an element to array at position. I found splice() method in javascript as a solution.

splice() can be used for adding/removing elements in array at given position.

Array.splice(position, numberOfElementsToRemoveFromPosition, ElementsToPushAtPosition)

Eg:
var array1=[1,2,3,4,5]

Adding at "0" added to 0th position
array1.splice(0,0,0)

array1 -> [0, 1, 2, 3, 4, 5]

Adding "6" at 6th position
array1.splice(6,0,6)

array1 -> [0, 1, 2, 3, 4, 5, 6]

Removing 2 elements from 2nd index , ie removing 2 and 3
array1.splice(2,2)
[2, 3]
array1 -> [0, 1, 4, 5, 6]

adding 2 elements at 2nd index , ie adding 2 and 3
array1.splice(2,0,2,3)
[]
array1 -> [0, 1, 2, 3, 4, 5, 6]

Removing "6" at 6th position and adding "7" and "8"
array1.splice(6,1,7,8)
[6]
array1 -> [0, 1, 2, 3, 4, 5, 7, 8]

References:
http://www.w3schools.com/jsref/jsref_splice.asp
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

No comments:

Post a Comment