Flatten an Array with ES2019 flat in JavaScript

Share this video with your friends

Send Tweet

ES2019 introduces the Array.prototype.flat method. In this lesson, we'll see how to flatten an array using Array.prototype.reduce and Array.prototype.concat, and then refactor the code to do the same thing using the .flat method.

J. Matthew
J. Matthew
~ 5 years ago

This is cool. Nice to see such a standard operation codified.

I was just going to ask why you needed to pass a depth at all—especially if you might not know it—since there's no reason the code couldn't keep recursing as long as some value were still an array, but don't worry, the method is already on it (from MDN):

var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Quick side-note: I'm not sure the lesson description text is right. It says "we'll see how to flatten an array using Array.prototype.reduce and Array.prototype.concat," but reduce is only used to sum the flattened array, and concat isn't used at all that I could spot.

Mike Sherov
Mike Sherov(instructor)
~ 5 years ago

since there's no reason the code couldn't keep recursing as long as some value were still an array

Infinite depth is not a safe default in the case of a self-referencing nested array, and also most nested arrays encountered in the wild aren't arbitrary depth. So that's why 1 was chosen as the default depth.