JavaScript | Flattening Arrays


If you have nested arrays one level deep and they need flattening, try this out…


// A nested array one-level deep
var array = [[ a, b ], [ c, d, e ], f, g];

// Using the built-in concat and apply functions
var flattened = [].concat.apply([],array);

// Output
console.log(flattened);
// [a, b, c, d, e, f]

Note: for infinitely nested Underscore.js has a flatten function

flatten_.flatten(array, [shallow]) Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will only be flattened a single level.


_.flatten([1, [2], [3, [[4]]]]);
=> [1, 2, 3, 4];

_.flatten([1, [2], [3, [[4]]]], true);
=> [1, 2, 3, [[4]]];    

Related Posts

Colours

Colour is an important part of design, here's a brief introduction to the world of colour, and how we can leverage this understanding in web design.

First tracks ever – written and recorded!

So last week I sat down and tried to write some songs, the first time I tried was years ago, and they were rubbish. I think these ones are a bit better, the one at the end of this post was inspired by living in China for a few years.

At long last – TTC

So this one’s for Ian, leaving Yangshuo after so long and having played thing song on his own and with the band countless times over the years, it’s finally gone digital!

Guilin Waterpark Gig

Probably our most fun gig to date was in Guilin Victory Park, a massive water park, a few square kilometres in area. We must have seen thousands of people there enjoying the rides and sunshine, everything in China seems to be on a completely different scale to the west, bigger, faster, longer, and definitely more crowded!

Home recording studio

For those of you not in China or don’t know about Taobao it’s basically eBay on steroids.

I’m a big faker

Definitely one of our strangest gigs. Well, if you could call it a gig. Five foreigners standing on a giant illuminated cityscape pretending to play along to a Bruno Mars track (of which I have ridded my mind of).

Tan Ka Guitar promo work

Whilst having some dinner at Alley Bar, quite possibly one of their very nice home-made pasta dishes, the Chinese owner asked if I’d be interested in recording some songs for a Shanghai-based guitar company.

Three Pigs

A day out on the rock at Yangshuo's latest crag.

Watch Out!

Definitely one of our strangest gigs. Well, if you could call it a gig. Five foreigners standing on a giant illuminated cityscape pretending to play along to a Bruno Mars track (of which I have ridded my mind of).

Pixyll in Action

See what the different elements looks like. Your markdown has never looked better. I promise.