The Question
What is the most efficient way to flatten an array in Javascript? This questions comes up often in interviews and also has ...
For further actions, you may consider blocking this person and/or reporting abuse
You could speed it up a little by counting and pre-allocating the array. Because that's going to be the slowest part of the classical for loop - the array allocations attributed to the pushes. Something like:
Can you test with the spread operator too?
And also using Array.prototype.flat ?
This last one is not available in all browsers (no Edge or IE).
I updated the test suite to take in the spread operator and flat() tests, but it didn't seem to be marketly faster than the others, actually flat seems like it is the slowest so far. You can see the results here.
I actually hadn't heard of the flat() function until you mentioned it. I had trouble getting it to work in my local node environment but was able to work it in Chrome. Not sure why.
It's not supported by Node :D
Thanks for the updated info!
Because some of the results bothered me, I took a look at the JSPerf. I saw some revisions to it since this article was posted. Erik Hughes found that for loop performance declines for large samples (10,000 arrays of 10 elements)
I modified the forEach a bit, found a solution that is middle-of-the-road performant regardless of array size (may be even better using push.apply over the spread operator):
All these tests need to take the
depthparameter into account, because the default is1....For me the concat-apply method is the fastest by far.

here's the test data: jsben.ch/z6nnv