2

I have two arrays:

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

I'd like to insert b at index 1 of a, to have :

c = [1,4,5,6,2,3]

Is there a builtin function to do this ? I found the answer for a single element, but not for a whole array. I imagine something like concat but with an additional parameter which would be the index of insertion.

Graham Slick
  • 6,692
  • 9
  • 51
  • 87

2 Answers2

4

var a = [1,2,3],
    b = [4,5,6];
    a.splice(1, 0, ...b);
    
    console.log(a);
kind user
  • 40,029
  • 7
  • 67
  • 77
4

Use Array#splice method.

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

// copy array a
c = a.slice();
// provide array of arguments using apply method
// and insert elements using splice method
[].splice.apply(c, [1, 0].concat(b))

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