Suggest an editImprove this articleRefine the answer for “Flat array from a multidimensional array”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**`arr.flat(depth)`** is a built-in array method (ES2019+) that "flattens" nested arrays to the given depth; by default it flattens one level of nesting, and `flat(Infinity)` flattens all levels regardless of depth. **Key point:** to fully flatten an array, use `arr.flat(Infinity)` - it is short, safe, and clear.Shown above the full answer for quick recall.Answer (EN)Image## 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 level - `flat(2)` -> two levels - `flat(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 `flatten` recursively. - 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: > > ```javascript > const flat = arr.flat(Infinity); > ``` > > - this is short, safe, and clear.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.