JavaScript - Inserting Multiple Items at Specific Index in JS Array
We can insert an item into Array at a specific index using the JavaScript Array splice method. This method removes the elements from the mentioned index and add items at that specific position.
1. Using array.splice() Method
JavaScript array.splice() Method is an inbuilt method in JavaScript that is used to modify the contents of an array by removing the existing elements and/or by adding new elements.
let a = [10, 20, 30, 40, 50];
const a1 = [99, 100, 101];
const a2 = 2;
a.splice(a2, 0, ...a1);
console.log(a);
Output
[ 10, 20, 99, 100, 101, 30, 40, 50 ]
2. Using JavaScript for Loop
The JavaScript for loop can be used to move all the elements from the index (where the new element is to be inserted) to the end of the array, one place after its current place. The required element can then be placed at the index.
let a = [10, 20, 30, 40, 50];
let idx = 2;
let a2 = [99, 100, 101];
for (let i = a.length; i > idx; i--) {
a[i + a2.length - 1] = a[i - 1];
}
for (let i = 0; i < a2.length; i++) {
a[idx + i] = a2[i];
}
console.log(a);
Output
[ 10, 20, 99, 100, 101, 30, 40, 50 ]
3. Using the concat() Method
The JavaScript concat() Method used to merge two or more arrays together. This method does not alter the original arrays passed as arguments but instead, returns a new Array.
let a = [10, 20, 30, 40, 50];
let i = 2;
let a1 = [99, 100, 101];
let a2 = a.slice(0, i).concat(a1, a.slice(i));
console.log(a2);
Output
[ 10, 20, 99, 100, 101, 30, 40, 50 ]
4. Using Spread Syntax With Array.slice() method
JS array.slice() method is used to select and return items as a new array. Create a new array by slicing before and after the index, then spread the new item between them.
let a = [10, 20, 30, 40, 50];
const i = 2;
const a1 = [99, 100, 101];
a = [...a.slice(0, i), ...a1, ...a.slice(i)];
console.log(a);
Output
[ 10, 20, 99, 100, 101, 30, 40, 50 ]
5. Using Array.from() Method
JS Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object. This method can be used to create a new array with the desired element inserted at the specified index.
let a = [10, 20, 30, 40, 50];
let a1 = [99, 100, 101];
let index = 2;
let a2 = Array.from(
{ length: a.length + a1.length },
(_, i) =>
i < index ? a[i] : i < index + a1.length ? a1[i - index] : a[i - a1.length]
);
console.log(a2);
Output
[ 10, 20, 99, 100, 101, 30, 40, 50 ]
6. Using Array.reduce() Method
The array.reduce() method iterates over the array and constructs a new array with the desired element inserted at the specified index.
const a = [1, 2, 3, 4, 5];
const index = 2;
const a1 = [99, 100, 101];
const a2 = a.reduce((acc, curr, i) => {
if (i === index) acc.push(...a1);
acc.push(curr);
return acc;
}, []);
console.log(a2);
Output
[ 1, 2, 99, 100, 101, 3, 4, 5 ]