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
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

  • By
    Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event...

Incredible Demos

  • By
    MooTools, mediaboxAdvanced, and Mexico

    The lightbox is probably one of my favorite parts of the Web 2.0 revolution. No more having to open new windows (which can bog down your computer quite a bit) to see a larger image, video, etc. Instead, the item loads right into the...

  • By
    MooTools Text Flipping

    There are lots and lots of useless but fun JavaScript techniques out there. This is another one of them. One popular April Fools joke I quickly got tired of was websites transforming their text upside down. I found a jQuery Plugin by Paul...

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!