Languages
[Edit]
EN

JavaScript - insert array inside another array

0 points
Created by:
Lily
548

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 ]

 

References

  1. Array.prototype.splice() - JavaScript | MDN
  2. Function.prototype.apply() - JavaScript | MDN
  3. Array.prototype.concat() - JavaScript | MDN

Alternative titles

  1. JavaScript - insert array inside another array at specific position
  2. JavaScript - add array to another array at specified position
  3. JavaScript - insert array elements inside another array at specific position
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join