Monday, May 20, 2024
160
rated 0 times [  161] [ 1]  / answers: 1 / hits: 87020  / 7 Years ago, mon, april 17, 2017, 12:00:00

We all know you can do:



let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5]


But how do you make this dynamic to concat N arrays?


More From » ecmascript-6

 Answers
5

One option is to use reduce:



let arrs = [[1, 2], [3, 4], [5, 6]];
arrs.reduce((a, b) => [...a, ...b], []);


Of course, this is a slow solution (quadratic time). Alternatively, if you can use Lodash, _.flatten does exactly what you want, and does it more efficiently (linear time).



EDIT



Or, adapted from Xotic750's comment below,



[].concat(...arrs);


Which should be efficient (linear time).


[#58123] Friday, April 14, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradleymoisesy

Total Points: 121
Total Questions: 105
Total Answers: 95

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
bradleymoisesy questions
Wed, Dec 22, 21, 00:00, 2 Years ago
Tue, Jun 1, 21, 00:00, 3 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;