0

I have two arrays:

let a = [1, 3, 5];
let b = [2, 4];

I need to put second array into first one after second element, so this is result:

[1, 3, 2, 4, 5]

What is the best way to insert second array into first in es6?

It can be easily solved using concat operation, but I am looking for nice way of doing it in es6.

ruslan5t
  • 257
  • 3
  • 16
  • I need to put second array at specific position, not in the end. – ruslan5t Jan 13 '17 at 16:29
  • @ruslan5t, please refer to [How to ask](http://stackoverflow.com/help/how-to-ask). It's easier to help if you give us all required criteria at the beginning, instead of editing the question and changing your issue later. – Wiktor Bednarz Jan 13 '17 at 16:42

3 Answers3

5

If you want to insert the second array at specific index, you can use splice function and spread operator.

var a = [1, 3, 5];
var b = [2, 4, 6];

a.splice(2, 0, ...b);

console.log(a); // [1, 3, 2, 4, 6, 5]
Wiktor Bednarz
  • 1,553
  • 10
  • 15
2

Use Array#splice method with spread syntax.

a.splice(2, 0, ...b)

let a = [1, 2, 5];
let b = [3, 4];

a.splice(2, 0, ...b);

console.log(a);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

I think this is the answer you're looking for:

function frankenSplice(arr1, arr2, n) {
    let arr3 = [...arr2];
    arr3.splice(n, 0, ...arr1);
    return arr3;
}
shieldgenerator7
  • 1,507
  • 17
  • 22