DEV Community

Ender İMEN
Ender İMEN

Posted on

.flat() & .flatMap()

I'm currently doing research on topics of interest to Javascript. When examining the features of ECMAScript 2019 (ES2019) / ES10, I came across the subject and liked it. I wanted to share it with you with the philosophy of sharing knowledge. 🤗

1.Array.flat ()

This method allows us to make our nested Array uniform and create a new Array.

Namely;

In this way, the depth (1, 2, 3,…) according to the value of the intertwined series, we can bring to the first level.

The lines of code on lines 3. and 4. actually do the same. Here, the parameter I liked was Infinity. Thanks to this feature, we can use our intertwined arrays, which have a complex structure, without giving depth parameters separately.

NOTE: With the flat() feature, we can also clear the empty fields in our corresponding array.

For example;

const numbers = [8,, 3, 19];

numbers.flat ();
// [8, 3, 19]

In ES6, this could be done in different ways for a depth array.

For example;

const oneLevelDeep = [8, [3], [19]];
const flattenedArray = [] .concat (... oneLevelDeep);

// or

const flattenedArray = [] .concat.apply ([], oneLevelDeep);
// Output: [8, 3, 19]

Recursive methods or Lodash,
Underscore libraries can do this process in a short way.

2. Array.flatMap()

This is the same as using .map() followed by .flat() or .flat(1). In short, .flatMap() maps each value to a new value, and then the resulting array becomes a maximum depth.

const fibonacci = [0, 1, 1, 2, 3];
fibonacci.map(f => [f, f * 2])
         .flat();

// [Array(2), Array(2), Array(2), …]
// 0: (2)[0, 0] 
// 1: (2)[1, 2]
// 2: (2)[1, 2]
// 3: (2)[2, 4]
// 4: (2)[3, 6]

// Output: [0, 0, 1, 2, 1, 2, 2, 4, 3, 6]

If we use .flatMap();

In short, considering the complex JSON result from the API, I can say that this is a very useful development.

const wish = ['stay', ['healthy', ['🖖']]];
console.log(wish.flat(Infinity));

Latest comments (0)