JessePinkman
JessePinkman

Reputation: 651

How to insert elements in an array at a particular index in case the elements are themselves in another array?

Suppose, I have two arrays :

A = [1, 2, 3, 4]

B = [10, 20, 30].

and I want to insert B's elements in array A starting from index 1. So, my final array would look like

[1, 10, 20, 30, 2, 3, 4]

I tried to do it with splice. But the splice function requires you to provide list of elements, not an array.

Is there any way to achieve it?

Upvotes: 1

Views: 51

Answers (3)

Shidersz
Shidersz

Reputation: 17190

You can also do this with Array.slice() and spread syntax. Note that Array.splice() mutates the array:

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

But, if you are looking to change array A then splice() is fine as shown on the other answers.

const A = [1, 2, 3, 4];
const B = [10, 20, 30];
const C = [...A.slice(0,1), ...B, ...A.slice(1)];
console.log(C);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

You can use splice with Function#apply method or ES6 spread syntax.

var A = [1, 2, 3, 4],

B = [10, 20, 30];

[].splice.apply(A,[1,0].concat(B));

console.log(A)

var A = [1, 2, 3, 4],

  B = [10, 20, 30];

A.splice(1, 0, ...B)

console.log(A)

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370729

You can just spread B into the argument list of splice:

const A = [1, 2, 3, 4]
const B = [10, 20, 30]
A.splice(1, 0, ...B); // equivalent to `.splice(1, 0, 10, 20 30)`
console.log(A);

Upvotes: 2

Related Questions