Introduction to flat and flatMap in javascirpt

Introduction to flat and flatMap in javascirpt

In this tutorial, we will learn about how to use and when to use the Flat() and FlatMap() method in JavaScript.

flat and flatMap method was introduced in es2019


The flat() method makes nested array into a single array

For example,

We have an nested array as follows:

 const arr = [[1, 2, 3], [4, 5, 6], 7, 8];

Now we can convert into one single array using flat method as follows:

const result = arr.flat();
//const result = arr.flat();

By default, the Flat method goes only one level deep,means it will not flat nested of nested array

However, We can change the depth as follows:



The flatMap() method essential combines map and flat map method which is better for performance.

Note: flatMap goes only one level deep we can't change it

For Example,

Suppose we have two arrays as follows:

const user = ['john', 'james', 'ali'];
const ages = [18, 45, 12];

Now we want to create new with the combination of users and theri ages, we can do this uusing flatmap as follows:

const mappedOnly =, index) => [animal, noises[index]]);
const mappedwithflat = user.flatMap((animal, index) => [animal, ages[index]]);
//["john", 18, "james", 45, "ali", 12]

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment