简体   繁体   中英

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?

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

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

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM