Flatten array with JavaScript reduce function

2 comments · 38% upvoted · source · other discussions

comments

helloiamsomeone

For the millionth time, stop generating a million intermediate array copies for a simple flatten operation.

This is part of the language now [1][2], but even for polyfill you should be using a stack based flatten.

wuchtelmesser

Nice to see that you're not creating new arrays in ever step of reduce like some of the more retarded solutions. It's still dumb (sorry, I've got a distaste for inneficient and illegible exploits of reduce) because you're doing nothing but a for loop with extra steps and you're still creating and merging arrays during the recursion.

This can be solved much more efficiently by passing the array as an argument to a recursive function, and then using loops to push relevant objects to the array. Or if you really must use reduce, use one single array instance as the array argument for all recursively invoked calls to reduce.