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.
In this example, we use apply()
to execute splice()
method on array1
and modify it by adding another array on insertIndex
position using concat()
.
xxxxxxxxxx
1
const array1 = [1, 2, 5, 6];
2
const array2 = [3, 4];
3
4
const insertIndex = 2;
5
6
array1.splice.apply(array1, [insertIndex, 0].concat(array2));
7
8
console.log(array1); // [ 1, 2, 3, 4, 5, 6 ]
In this example, we present an alternative solution that uses splice()
method with spread syntax (...
).
xxxxxxxxxx
1
const array1 = [1, 2, 5, 6];
2
const array2 = [3, 4];
3
4
const insertIndex = 2;
5
6
array1.splice(insertIndex, 0, array2);
7
8
console.log(array1); // [ 1, 2, 3, 4, 5, 6 ]