flat()
ES2019+Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Syntax
array.flat(depth)Parameters
depth number optionalThe depth level specifying how deep a nested array structure should be flattened (default: 1)
Return Value
A new array with the sub-array elements concatenated
Examples
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat());
console.log(nested.flat(2)); 📌 When to Use
Use flat() when you need to reduce the nesting level of an array. It's perfect for flattening nested data structures, simplifying arrays of arrays, or processing hierarchical data into a flat list.
⚠️ Common Mistakes
Forgetting the depth parameter - flat() only flattens one level by default
Using Infinity depth unnecessarily - may cause performance issues with very deep nesting
Expecting flat() to remove undefined/null values - use filter() for that
✅ Best Practices
Use flat(Infinity) to completely flatten deeply nested arrays
flat() also removes empty slots in arrays: [1,,2].flat() gives [1,2]
Use flatMap() when you need to map and flatten in one step
⚡ Performance Notes
flat() creates a new array and is O(n) where n is the total number of elements after flattening. For large nested arrays, be mindful of memory usage. Consider using a generator or iterative approach for very large data sets.
🌍 Real World Example
Combining Results from Multiple API Calls
Flatten arrays of results from parallel API calls into a single list
// Fetch users from multiple pages in parallel
const pagePromises = [
fetchUsers(page: 1),
fetchUsers(page: 2),
fetchUsers(page: 3)
];
const pagesOfUsers = await Promise.all(pagePromises);
// [[user1, user2], [user3, user4], [user5, user6]]
const allUsers = pagesOfUsers.flat();
// [user1, user2, user3, user4, user5, user6]
// Deeply nested example
const nested = [[1, [2, [3, [4]]]]];
const completelyFlat = nested.flat(Infinity);
// [1, 2, 3, 4]