Last updated Apr 13, 2021

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.

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

flat():

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();
console.log(result);
//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:

arr.flat(2);

flatMap():

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 = user.map((animal, index) => [animal, noises[index]]);
console.log(mappedOnly);
//[["john",18],["james",45],["ali",12]]
const mappedwithflat = user.flatMap((animal, index) => [animal, ages[index]]);
console.log(mappedwithflat);
//["john", 18, "james", 45, "ali", 12]

Tags

Available for projectsLet’s build together

Need this built properly,
not just explained?

I take on Angular and NestJS work directly — auth systems, multi-tenant SaaS, API rewrites and the deploy pipeline underneath them. You talk to the person writing the code.

Projects delivered
20+ Projects delivered
Angular • NestJS
7+ years Angular • NestJS
Average reply time
1 day Average reply time

What I can help with

  • Auth and permissions systems
  • Multi-tenant SaaS foundations
  • API design and rewrites
  • Deploy pipelines and VPS setup
  • Bug fixing and performance optimization
Send me a message

Tell me about your project and I’ll get back with a realistic scope and price.

Turn
Your Ideas
Into Reality

Stay in the loop

Get the finished tutorials, projects and resources in your inbox.

Join 5,000+ developers and get new tutorials, source code, product updates and exclusive content — straight to your inbox.

  • No spam
  • Useful content only
  • Unsubscribe anytime

Subscribe to TutsCoder

Be the first to get new tutorials, projects and tips.

Join 5,000+ developers already learning with us.

Learn
Build
Grow

Discussion

Comments

Share your thoughts, ask questions or suggest improvements. Let’s learn and grow together!

Loading comments…

Join the discussion

Sign in to join the discussion. Your account also keeps your saved tutorials and path progress.