Given an array and index, the task is to insert a particular item at given index. There are multiple ways to insert an item into an array at a specific index in JavaScript.
1. Using the splice() Method
The splice() method
is used to modify the arrays. 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 the Spread Operator (…)
The spread operator
can be used to create a new array by spreading the elements from an existing array 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
The for loop
can also be used 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
can combine multiple arrays into one, making it 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 ]