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.
If 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 comments 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With