Flat array from a multidimensional array
Example:
javascript
const arr = [1, [2, 3], [4, [5, 6]]];We want to get -> [1, 2, 3, 4, 5, 6]
1. The simplest way - .flat() (ES2019+)
javascript
const flattened = arr.flat();
console.log(flattened); // [1, 2, 3, 4, [5, 6]]By default flat() "flattens" only one level of nesting.
2. Specify the flattening depth
javascript
const deeplyFlattened = arr.flat(2);
console.log(deeplyFlattened); // [1, 2, 3, 4, 5, 6]flat(1)-> one levelflat(2)-> two levelsflat(Infinity)-> completely, regardless of depth
Example:
javascript
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat(Infinity)); // [1, 2, 3, 4]This is the most convenient and modern way to "flatten" an array.
3. Alternative - recursion (the old way, before flat)
javascript
function flatten(arr) {
return arr.reduce(
(acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val),
[]
);
}
console.log(flatten([1, [2, [3, 4]], 5]));
// [1, 2, 3, 4, 5]- We check each element:
if it's an array -> call
flattenrecursively. - If not -> add it to the result.
4. Via toString() (only for numbers/strings)
javascript
[1, [2, [3, 4]]].toString().split(',');
// ["1", "2", "3", "4"]Works only if there are no objects or null,
because everything is turned into strings.
5. Via flatMap() (for combining + flatten)
javascript
const arr = [1, 2, [3, 4]];
const result = arr.flatMap(x => (Array.isArray(x) ? x : [x]));
console.log(result); // [1, 2, 3, 4]flatMap() simultaneously transforms elements and flattens one level.
Short version:
| Method | Works with | Depth | Mutates | Modern |
|---|---|---|---|---|
arr.flat() | array | 1 by default | No | Yes (ES2019+) |
arr.flat(Infinity) | multidimensional | all levels | No | Yes |
| Recursion | array | any | No | Yes (universal) |
flatMap() | array | 1 level | No | Yes |
toString().split() | numbers, strings | all levels | No | limited |
Conclusion: To "flatten" an array:
javascriptconst flat = arr.flat(Infinity);
- this is short, safe, and clear.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.