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()
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)
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .