Today I Learned

hashrocket A Hashrocket project

Flatten array in javascript

Flattening an array with nested arrays (2 dimensional array) in javascript is relatively easy if unintuitive.

> [].concat.apply([], [[1],[2,3],[4]])
[ 1, 2, 3, 4 ]

But an array with 3 or more dimensions or levels of nesting gets messy.

> [].concat.apply([], [[1], [2, [3]]])
[ 1, 2, [ 3 ] ]

This Stack Overflow thread has some solutions. This underscore implementation is a good reference as well.

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.