Recursive Array.flat

By  on  

There was much talk about Array.prototype.flat during its early stages, starting with the name alone. Many developers preferred the name flatten but the spec differed from MooTools' implementation. MooTools would recursively flatten an array but the new, official flat implementation defaults one level of flattening,.

The current implementation of Array.prototype.flat is:

[1, 2, [3], [[4]]].flat(/* depth */);
// [1,2,3,[4]]

.flat only flattens arrays to one level by default, but what if you want a truly flattened array? You can use Infinity and flat's depth argument to make that happen:

[1, 2, [3], [[4]], [[[[[[6]]]]]]].flat(Infinity);
// [1,2,3,4,6]

I find the method name a bit misleading but I understand why they went to a single level. The method name smush was thrown around, which would've been the worst method name since stringify!

Recent Features

  • By
    Conquering Impostor Syndrome

    Two years ago I documented my struggles with Imposter Syndrome and the response was immense.  I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions.  I've even caught myself reading the post...

  • By
    Regular Expressions for the Rest of Us

    Sooner or later you'll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In...

Incredible Demos

  • By
    Making the Firefox Logo from HTML

    When each new t-shirt means staving off laundry for yet another day, swag quickly becomes the most coveted perk at any tech company. Mozilla WebDev had pretty much everything going for it: brilliant people, interesting problems, awesome office. Everything except a t-shirt. That had to change. The basic...

  • By
    Upload Photos to Flickr with PHP

    I have a bit of an obsession with uploading photos to different services thanks to Instagram. Instagram's iPhone app allows me to take photos and quickly filter them; once photo tinkering is complete, I can upload the photo to Instagram, Twitter, Facebook, and...

Discussion

  1. Array.prototype.flat

    have an argument to specify the depth (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat#Parameters):

    [1, 2, [3], [[4]], [[[[[[6]]]]]]].flat(Infinity); // [1,2,3,4,6]

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!