1

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?

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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;}

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.