The Array.prototype.flat() method (introduced in ES2019) is a powerful tool designed to simplify multidimensional arrays. It creates a new array by recursively concatenating sub-array elements into it up to a specified depth.
Before flat(), developers had to use complex reduce() and concat() logic or external libraries to “un-nest” data structures.
1. Syntax and the Depth Parameter
The method takes one optional argument: depth.
const newArray = array.flat(depth);
- depth (Optional): An integer specifying how many levels of a nested array should be flattened. The default value is 1.
- Return Value: A new array with the sub-array elements concatenated into it. The original array remains unmutated.
Basic Examples
const arr1 = [1, 2, [3, 4]];
console.log(arr1.flat()); // [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]];
console.log(arr2.flat()); // [1, 2, 3, 4, [5, 6]] (Only 1 level deep by default)
console.log(arr2.flat(2)); // [1, 2, 3, 4, 5, 6]
2. Flattening All Levels (Infinity)
If you have an array with an unknown or deeply nested structure and you want to reduce it to a single dimension, you can pass Infinity as the depth argument.
const deepArr = [1, [2, [3, [4, [5]]]]];
const flatArr = deepArr.flat(Infinity);
console.log(flatArr); // [1, 2, 3, 4, 5]
3. Automatic Data Cleaning: Handling Sparse Arrays
A unique and highly useful feature of flat() is that it automatically removes empty slots (holes) in sparse arrays. It does not remove null or undefined values, only indices that have never been assigned a value.
[Image comparing sparse array behavior in map vs flat method]
const sparseArray = [1, , 3, [4, , 6]];
// Flattens and removes the hole at index 1
console.log(sparseArray.flat()); // [1, 3, 4, undefined, 6]
// Note: The hole inside the sub-array was flattened into an 'undefined'
// or removed depending on the engine's interpretation of sub-array holes.
4. Data Transformation
In modern web development, data often arrives from APIs in “grouped” formats. For instance, you might have a list of categories, each containing a list of products. If you want a master list of all products, flat() is the ideal solution.
const categories = [
{ name: "Electronics", items: ["Laptop", "Phone"] },
{ name: "Books", items: ["Novel", "Biography"] }
];
// Map out the item arrays, then flatten
const allItems = categories.map(c => c.items).flat();
console.log(allItems);
// ["Laptop", "Phone", "Novel", "Biography"]
5. Real-World Use Case: Handling API Responses
Imagine an API returns a list of categories, and each category has an array of products. If you want a master list of all products across all categories, flat() is your best friend.
const categories = [
{ name: "Electronics", products: ["TV", "Radio"] },
{ name: "Furniture", products: ["Chair", "Table"] }
];
const allProducts = categories.map(cat => cat.products).flat();
// Result: ["TV", "Radio", "Chair", "Table"]
