Which is a better and more efficient way to flatten multiple arrays into one?
Spread operator:
let arr = [];
for (const array of arrays) {
arr.push(…array);
}
Or with .flat()
:
let arr = [];
for (const array of arrays) {
arr.push(array);
}
arr = arr.flat();
I am using a loop instead of just const arr = arrays.flat()
because I want to test something very specific.
Which is a better and more efficient way to flatten multiple arrays into one?
Spread operator:
let arr = [];
for (const array of arrays) {
arr.push(…array);
}
Or with .flat()
:
let arr = [];
for (const array of arrays) {
arr.push(array);
}
arr = arr.flat();
I am using a loop instead of just const arr = arrays.flat()
because I want to test something very specific.
-
You have to test it, but I guess
.flat()
is more efficient as it's implemented by the browser, thus written in C/C++ and better optimized. – Guerric P Commented Jul 11, 2021 at 20:29 -
1
why not just
const arr = arrays.flat()
? No need for your loop (which should be lowercasefor
). – pilchard Commented Jul 11, 2021 at 20:34 - @plichard l’m from mobile, that’s why I got “for” with upper case.. And I wanted to test something very specific, that’s why I want it with for loop. – Maor agai Commented Jul 11, 2021 at 20:42
-
...
spreads one level only. It has a different purpose fromArray.prototype.flat
– Aluan Haddad Commented Jul 11, 2021 at 20:48 -
1
flat
flattens to arbitrary depth....
does does something pletely different. Performance is irrelevant when paring operations that are not analogous – Aluan Haddad Commented Jul 11, 2021 at 20:49
2 Answers
Reset to default 8If you need single-level flattening, according to this JSBench I cooked up,
let arr = [].concat(...arrays);
is by far the fastest (on my Windows Chrome 93, according to ments not so on Safari), more than 3x the speed of your implementation.
Running the same bench as the accepted answer, that solution is faster than the others tested, but I tested a couple of others and found another solution that is around ~12% faster:
let arr = [].concat.apply([], arrays);
Benchmark testing: https://jsbench.me/adlib26t2y/2