Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  29] [ 7]  / answers: 1 / hits: 130166  / 13 Years ago, thu, august 11, 2011, 12:00:00

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.


More From » arrays

 Answers
51

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

[#90664] Wednesday, August 10, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
luna

Total Points: 698
Total Questions: 114
Total Answers: 93

Location: Israel
Member since Wed, Apr 14, 2021
3 Years ago
luna questions
;