Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS insert into array at specific index [duplicate]

I would like to insert a string into an array at a specific index. How can I do that?

I tried to use push()

like image 565
lilly Avatar asked Aug 15 '15 11:08

lilly


1 Answers

Well, thats pretty easy. Assuming you have an array with 5 objects inside and you want to insert a string at index 2 you can simply use 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 now:

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

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

like image 143
nils Avatar answered Oct 22 '22 19:10

nils