Insert JS into an array at a specific index

I would like to insert a string into an array with a specific index. How can i do this?

I tried using push ()

+6
source share
1 answer

Well, that is pretty easy. Assuming you have an array with 5 objects inside and you want to insert a row into index 2, you can simply use the javascripts array splice method:

var array = ['foo', 'bar', 1, 2, 3], insertAtIndex = 2, stringToBeInserted = 'someString'; // insert string 'someString' into the array at index 2 array.splice( insertAtIndex, 0, stringToBeInserted ); 

Your result will be as follows:

 ['foo', 'bar', 'someString', 1, 2, 3] 

FYI: the push () method you used just adds new elements to the end of the array (and returns the new length)

+12
source

All Articles