JavaScript
Overview of JavaScript ES2019 array flat function explaining how to flatten nested arrays using array.flat with depth levels Infinity behavior and caveats.
Array.Prototype.Flat() or ES2019 Array Flat() function ZeptoBook
Wireframe overlay treatment: cyan-tinted annotation over matte navy field.
Rating: 3.6 / 5
Signal strength measured across clarity, contrast, and geometry consistency.

JavaScript

There are new features introduced in JavaScript ES2019. In this blog I will discuss Array.prototyeflat() or ES2019 array flat() function. How array.prototype.flat() or flat() function can make programmers life easier.

Flattening array in JavaScript Flattening arrays may not be an everyday need but it is still an important need enough to be part of most utility libraries in JavaScript. Take a look at the embedded array let array 1 2 3 4 5 6 and we want result like this 1 2 3 4 5 6 To be honest it becomes a nightmare to deal with such an array. Before ES2019 flat() function there were few classical ways to deal with this monster.

The Old Classical ways Lets explore all the possible old classical ways of dealing with this monster array. Here you go Using reduce() var result array.reduce(function(prev curr) { return prev.concat(curr); }); Using concat() and apply() var result concat.apply( array); Using reduce() var result array.reduce(function(prev curr) { return prev.concat(curr); }); Using ES6 Spread Operator var result concat(...array);

The new magical way of Array.Prototype.Flat() or ES2019 Flat() function Array.prototype.flat() The JavaScript array flat() function helps you to concatenate all subarray elements of an array. In other words it returned a flatten version of an array. Use array.flat() to get the flattened version of the array. array.flat() 1 2 3 4 5 6 In another way you can pass the depth level. By default it is 1. So above can be written like below as well. array.flat(1) 1 2 3 4 5 6 But still we did not get our result. No problem lets move to next depth level say 2. array.flat(2) 1 2 3 4 5 6 Hurray We got our result without any pain in the neck.

How to deal with complex depth level here is the resue Infinity If you are not sure about array depth level or you dont get into this crap use Infinity as a flat parameter. Trust me it will save your time. Wonderful const array 1 2 3 4 5 6 7 8 9 10 11 12 array.flat(Infinity) 1 2 3 4 5 6 7 8 9 10 11 12

Caution Note that if there is any empty slot in the array the JavaScript array.flat() function will discard these empty slot while flattening them. Take a look at below example const array a b c d array.flat() a b c d

Reference v8.devfeaturesarrayflatflatmap

Further Reading Type Interference In TypeScript Destructuring In JavaScript Can Make Your Code Short And Cleaner This Is Why Learning New JavaScript ES6 Syntax Is So Famous

Next
Contacts: Request review
COMMENTS
No comments yet. This block is reserved for a future threaded system.
Return to top