flat and flatMap
This lesson explains flat and flatMap with clear examples, use cases, and best practices so you can use modern JavaScript confidently in real projects.
ES6 Array flat() and flatMap() Overview
flat() and flatMap() are modern JavaScript array
methods used to work with nested arrays. The flat() method
removes nested array levels, while flatMap() maps each item
and then flattens the result by one level.
These methods are commonly used for API responses, nested menu data,
product categories, search results, tags, comments, permissions, dashboard
widgets, and data transformation in React, Angular, Vue, Node.js, and
full-stack applications.
| Method | Purpose | Returns | Mutates Original? |
flat() | Flattens nested arrays. | New array. | No. |
flatMap() | Maps items and flattens one level. | New array. | No. |
Basic flat() Example
const numbers =
[
1,
2,
[
3,
4
]
];
const result =
numbers.flat();
console.log(result);
// [1, 2, 3, 4]
By default, flat() removes one level of nesting.
flat() with Depth
const nested =
[
1,
[
2,
[
3,
[
4
]
]
]
];
const result =
nested.flat(2);
console.log(result);
// [1, 2, 3, [4]]
The depth value tells JavaScript how many nested levels should be
flattened.
Flatten All Levels with Infinity
const deeplyNested =
[
1,
[
2,
[
3,
[
4,
[
5
]
]
]
]
];
const result =
deeplyNested.flat(Infinity);
console.log(result);
// [1, 2, 3, 4, 5]
Use Infinity when the nesting depth is unknown.
flat() Removes Empty Slots
const values =
[
1,
,
2,
[
3,
,
4
]
];
const result =
values.flat();
console.log(result);
// [1, 2, 3, 4]
flat() removes empty slots from arrays while flattening.
Basic flatMap() Example
const numbers =
[
1,
2,
3
];
const result =
numbers.flatMap(
number =>
[
number,
number * 2
]
);
console.log(result);
// [1, 2, 2, 4, 3, 6]
flatMap() is similar to calling map() followed
by flat(1).
flatMap() vs map().flat()
const numbers =
[
1,
2,
3
];
const usingMapFlat =
numbers
.map(
number =>
[
number,
number * 2
]
)
.flat();
const usingFlatMap =
numbers.flatMap(
number =>
[
number,
number * 2
]
);
console.log(usingMapFlat);
console.log(usingFlatMap);
flatMap() is shorter and often easier to read when mapping
creates arrays.
flatMap() Flattens Only One Level
const numbers =
[
1,
2
];
const result =
numbers.flatMap(
number =>
[
number,
[
number * 10
]
]
);
console.log(result);
// [1, [10], 2, [20]]
flatMap() always flattens only one level. Use
flat() separately if deeper flattening is required.
Split Sentences into Words
const sentences =
[
"Learn JavaScript",
"Practice ES6"
];
const words =
sentences.flatMap(
sentence =>
sentence.split(" ")
);
console.log(words);
// ["Learn", "JavaScript", "Practice", "ES6"]
This is a common real-world use case for text processing and search
indexing.
Flatten API Response Data
const response =
[
{
category: "Electronics",
products:
[
"Laptop",
"Phone"
]
},
{
category: "Furniture",
products:
[
"Desk",
"Chair"
]
}
];
const products =
response.flatMap(
category =>
category.products
);
console.log(products);
Flatten User Permissions
const roles =
[
{
role: "admin",
permissions:
[
"read",
"write",
"delete"
]
},
{
role: "editor",
permissions:
[
"read",
"write"
]
}
];
const permissions =
roles.flatMap(
role =>
role.permissions
);
console.log(permissions);
Remove Items with flatMap()
const numbers =
[
1,
2,
3,
4
];
const oddNumbers =
numbers.flatMap(
number => {
if (number % 2 === 0) {
return [];
}
return [number];
}
);
console.log(oddNumbers);
// [1, 3]
Returning an empty array removes an item from the final result.
Expand Items with flatMap()
const products =
[
"Laptop",
"Phone"
];
const result =
products.flatMap(
product =>
[
product,
product + " Warranty"
]
);
console.log(result);
Returning multiple values expands one item into many items.
flatMap() Callback Parameters
const values =
[
"A",
"B",
"C"
];
const result =
values.flatMap(
(
value,
index,
array
) => {
console.log(value);
console.log(index);
console.log(array);
return [value];
}
);
The callback receives the current value, index, and original array.
flat() vs flatMap()
| Feature | flat() | flatMap() |
| Main Purpose | Flatten nested arrays. | Transform and flatten one level. |
| Callback | No callback. | Requires callback. |
| Depth Control | Supports depth. | Only one level. |
| Equivalent To | Flattening only. | map() + flat(1). |
| Best Use | Nested array cleanup. | Mapping into multiple values. |
Real-World Use Cases
-
Flatten nested API response arrays.
-
Extract all tags from blog posts.
-
Flatten menu children.
-
Combine product variants.
-
Build search indexes from sentences.
-
Extract permissions from roles.
-
Normalize dashboard widget data.
-
Convert nested comments into flat lists.
-
Expand one record into multiple display rows.
-
Remove items by returning empty arrays from
flatMap().
Common Mistakes
-
Expecting
flat() to flatten all levels by default.
-
Forgetting that
flatMap() flattens only one level.
-
Using
flatMap() when simple map() is enough.
-
Returning non-array values without understanding the final result.
-
Overusing
flat(Infinity) on very large arrays.
-
Assuming these methods mutate the original array.
-
Creating unclear callback logic inside
flatMap().
-
Forgetting browser support or polyfills for older environments.
Best Practices
-
Use
flat() when data is already nested.
-
Use
flatMap() when each item must be transformed into zero,
one, or many values.
-
Use explicit depth values for better readability.
-
Use
flat(Infinity) only when nesting depth is unknown.
-
Keep
flatMap() callbacks simple.
-
Combine
flatMap() with Set for unique lists.
-
Avoid flattening extremely large arrays repeatedly.
-
Prefer readable transformation steps over overly clever one-liners.
Interview Questions
-
What does
flat() do?
-
What is the default depth of
flat()?
-
How do you flatten all nested levels?
-
What does
flatMap() do?
-
How is
flatMap() different from
map().flat()?
-
Does
flatMap() flatten deeply nested arrays?
-
Do
flat() and flatMap() mutate the original
array?
-
When should
flatMap() be preferred over
map()?
-
How can
flatMap() remove items from an array?
-
What are real-world use cases for these methods?
Key Takeaways
-
flat() converts nested arrays into flatter arrays.
-
flat() flattens one level by default.
-
flat(Infinity) flattens all levels.
-
flatMap() maps each item and flattens the result by one
level.
-
Both methods return new arrays and do not mutate the original array.
-
Use these methods for nested API data, tags, menus, permissions, and
transformed lists.
Pro Tip
Use flat() when your data is already nested, and use
flatMap() when your mapping function returns arrays. For
interviews, remember this simple rule: flatMap() is
map() plus flat(1).