Computer >> Computer tutorials >  >> Programming >> Javascript

How to insert an item into an array at a specific index in javaScript?


For inserting at the end of an array, we can use the push method. For inserting at the beginning of the array we can use the unshift method. For inserting at other positions, we can use the splice method.

Let us look at the examples of each of these −

Push

Example

let arr = ["test", 1, 2, "hello", 23.5];
arr.push(123);
console.log(arr);

Output

[ 'test', 1, 2, 'hello', 23.5, 123 ]

Unshift −

Example

let arr = ["test", 1, 2, "hello", 23.5];
arr.unshift(123);
console.log(arr);

Output

[ 123, 'test', 1, 2, 'hello', 23.5 ]

Splice

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. We can use it to insert elements at given indices in the following way −

Example

let arr = ["test", 1, 2, "hello", 23.5];
// Replace 0 elements(can also be interpreted as insert) at index 2 with 123
arr.splice(2, 0, 123);
console.log(arr);

Output

[ 'test', 1, 123, 2, 'hello', 23.5 ]