How to insert an item into array at specific index in JavaScript ?
There are multiple ways to insert an item into an array at a specific index in JavaScript:
- Using the
splice()
method: Thesplice()
method can be used to add or remove elements from an array. To insert an item at a specific index, we can use thesplice()
method with the index and 0 as the second argument, followed by the item we want to insert. Here's an example:
let arr = [1, 2, 3, 4];
arr.splice(2, 0, 5);
console.log(arr); // Output: [1, 2, 5, 3, 4]
In the above example, we are inserting the number 5 at index 2 of the array arr
.
- Using the
slice()
andconcat()
methods: We can also use theslice()
method to split the array into two parts, and then use theconcat()
method to join the two parts with the item we want to insert. Here's an example:
let arr = [1, 2, 3, 4];
let newArr = arr.slice(0, 2).concat(5, arr.slice(2));
console.log(newArr); // Output: [1, 2, 5, 3, 4]
In the above example, we are splitting the array arr
into two parts: [1, 2]
and [3, 4]
. We then use the concat()
method to join the first part with the number 5 and the second part, resulting in the new array [1, 2, 5, 3, 4]
.
- Using the
unshift()
andsplice()
methods: We can also use theunshift()
method to add the item to the beginning of the array, and then use thesplice()
method to move the item to the desired index. Here's an example:
let arr = [1, 2, 3, 4];
arr.unshift(0);
arr.splice(2, 0, 5);
console.log(arr); // Output: [0, 1, 5, 2, 3, 4]
In the above example, we are adding the number 0 to the beginning of the array using the unshift()
method. We then use the splice()
method to insert the number 5 at index 2 of the array, resulting in the new array [0, 1, 5, 2, 3, 4]
.