Nov 21, 2016 - Flattening multi-dimensional arrays in JavaScript is no longer a headache. Thank you ES6 (or ES2015, whatever!).
![Javascript Javascript](/uploads/1/2/5/4/125420065/300904739.jpg)
I've noticed that people are using recursions which are not cost friendly, especially with new ES6 standards giving us the power of spread operators. When you're pushing the items into the master array just use. And it will automatically add flattened objects. Something like array.push(.subarray1) // subarray1 = object1, object2 array.push(.subarray2) // subarray2 = object3 array.push(.subarray3) // subarray3 = object4,object5, object6 // output - array = object1, object2, object3, object4, object5, object6.
![Object Object](/uploads/1/2/5/4/125420065/208081327.png)
Is the performance test for these two and couple more approaches (one suggested by @elclanrs in the comments). The performance differences will vary significantly across different browsers, and even different version on same browser, as browser these days try to optimize javascript very aggressively. Unless you are dealing with very large arrays or this operation is performed repeatedly in quick succession, I would suggest you to use simplest and clearest approach. But, that being said the loop solution is also not that complex or big anyway (and it performs better than others especially on firefox). $ begingroup $ The limit is there to overcome the stack limitation.
For arrays larger than 32768, applying the concat function like this will result in the JS engine throwing an error because the call stack will exceed the 32k limit as it recurses. See my comment to elclanrs regarding his solution using concat in the discussion at the top. If you are never going to encounter arrays that large, the limit checking code isn't needed and you can just use concat directly.
$ endgroup $ – May 30 '18 at 15:31.