Given an array and index, the task is to insert a particular item at a given index. There are multiple ways to insert an item into an array at a specific index in JavaScript.
1. Using splice() Method
The splice() method
is used to modify the original array. This method can be used to insert, remove, or replace elements in an array.
const arr = [10, 20, 30, 40, 50];
// Insert 25 at index 2
arr.splice(2, 0, 25);
console.log(arr);
// Output: [ 10, 20, 25, 30, 40, 50 ]
2. Using Spread Operator (…)
The spread operator
is used to create a new array by spreading the existing array elements and adding new items at specific positions.
const arr = [10, 20, 30, 40, 50];
// Insert 25 at index 2
const newArr = [...arr.slice(0, 2), 25, ...arr.slice(2)];
console.log(newArr);
// Output: [ 10, 20, 25, 30, 40, 50 ]
3. Using for Loop
We can also use for loop
to insert an item at given index in an array. The for loop can be used to shift the array elements and insert the new item.
const arr = [10, 20, 30, 40, 50];
const index = 2;
const newItem = 25;
// Shift elements to the right
for (let i = arr.length; i > index; i--) {
arr[i] = arr[i - 1];
}
// Insert the new item
arr[index] = newItem;
console.log(arr);
// Output: [ 10, 20, 25, 30, 40, 50 ]
4. Using Array concat() Method
The concat() method
combines multiple arrays into one array. It is suitable for inserting an item by combining slices of the original array with the new item.
const arr = [10, 20, 30, 40, 50];
const newItem = 25;
const newArr = arr.slice(0, 2)
.concat(newItem)
.concat(arr.slice(2));
console.log(newArr);
// Output: [ 10, 20, 25, 30, 40, 50 ]