Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of Array.flat() vs spread operator to flatten multiple arrays into one

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.

like image 667
Maor agai Avatar asked Oct 25 '25 09:10

Maor agai


2 Answers

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.

like image 122
AKX Avatar answered Oct 28 '25 00:10

AKX


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

like image 22
Brandon McConnell Avatar answered Oct 28 '25 00:10

Brandon McConnell