EN
JavaScript - insert array inside another array
0
points
In this article, we would like to show you how to insert an array inside another array at a specific position in JavaScript.
1. Using splice() with apply() and concat()
In this example, we use apply() to execute splice() method on array1 and modify it by adding another array on insertIndex position using concat().
// ONLINE-RUNNER:browser;
const array1 = [1, 2, 5, 6];
const array2 = [3, 4];
const insertIndex = 2;
array1.splice.apply(array1, [insertIndex, 0].concat(array2));
console.log(array1); // [ 1, 2, 3, 4, 5, 6 ]
2. Using splice() with spread syntax (ES6)
In this example, we present an alternative solution that uses splice() method with spread syntax (...).
// ONLINE-RUNNER:browser;
const array1 = [1, 2, 5, 6];
const array2 = [3, 4];
const insertIndex = 2;
array1.splice(insertIndex, 0, ...array2);
console.log(array1); // [ 1, 2, 3, 4, 5, 6 ]