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
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

  • By
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

Incredible Demos

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!