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
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

  • By
    5 More HTML5 APIs You Didn’t Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

Incredible Demos

  • By
    WordPress-Style Comment Controls Using MooTools or jQuery

    WordPress has a nice little effect on the Admin Dashboard where it shows and hides the comment control links when you mouseover and mouseout of the record's container. Here's how to achieve that effect using MooTools or jQuery. The XHTML Notice that we place the links into...

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

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!