Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - insert an array inside another array

What is the more efficient way to insert an array inside another array.

a1 = [1,2,3,4,5]; a2 = [21,22];  newArray - a1.insertAt(2,a2) -> [1,2, 21,22, 3,4,5]; 

Iterating a2 using splice looks a bit awfull from a performance point of view if a2 array is large.

Thanks.

like image 717
ic3 Avatar asked Aug 11 '11 20:08

ic3


People also ask

Can you put an array inside an array JavaScript?

An array is an ordered collection of values: each value is called an element, and each element has a numeric position in the array, known as its index. JavaScript lets us create arrays inside array called Nested Arrays.


1 Answers

You can use splice combined with some apply trickery:

a1 = [1,2,3,4,5]; a2 = [21,22];  a1.splice.apply(a1, [2, 0].concat(a2));  console.log(a1); // [1, 2, 21, 22, 3, 4, 5]; 

In ES2015+, you could use the spread operator instead to make this a bit nicer

a1.splice(2, 0, ...a2); 
like image 78
nickf Avatar answered Sep 23 '22 17:09

nickf