0
0
JavascriptHow-ToBeginner · 3 min read

How to Flatten Nested Array in JavaScript Easily

You can flatten a nested array in JavaScript using the Array.flat() method, which removes nested levels up to a specified depth. For deeper or unknown nesting, use a recursive function to flatten all levels into a single array.
📐

Syntax

The Array.flat(depth) method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

  • depth: Optional. The number of levels to flatten. Default is 1.
  • Returns a new flattened array.
javascript
const flattenedArray = nestedArray.flat(depth);
💻

Example

This example shows how to flatten a nested array with two levels using flat() and how to flatten deeply nested arrays using a recursive function.

javascript
const nestedArray = [1, [2, 3], [4, [5, 6]]];

// Using flat() with depth 2
const flatTwoLevels = nestedArray.flat(2);
console.log(flatTwoLevels); // Output: [1, 2, 3, 4, 5, 6]

// Recursive flatten function for any depth
function flattenDeep(arr) {
  return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}

const fullyFlattened = flattenDeep(nestedArray);
console.log(fullyFlattened); // Output: [1, 2, 3, 4, 5, 6]
Output
[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
⚠️

Common Pitfalls

One common mistake is using flat() without specifying enough depth, which results in partially flattened arrays. Another is trying to flatten arrays with unknown depth without recursion.

Also, flat() is not supported in very old browsers, so polyfills or recursion might be needed.

javascript
const arr = [1, [2, [3, 4]]];

// Wrong: flat() with default depth 1
console.log(arr.flat()); // Output: [1, 2, [3, 4]] (not fully flattened)

// Right: flat() with depth 2
console.log(arr.flat(2)); // Output: [1, 2, 3, 4]
Output
[1, 2, [3, 4]] [1, 2, 3, 4]
📊

Quick Reference

  • Array.flat(depth): Flattens array up to depth levels.
  • Recursive flatten: Use when depth is unknown or infinite.
  • Check browser support: flat() works in modern browsers.

Key Takeaways

Use Array.flat(depth) to flatten arrays up to a known depth easily.
For unknown or deep nesting, use a recursive function to flatten all levels.
Always specify the depth in flat() to avoid partial flattening.
Check browser compatibility for flat() or use recursion as fallback.
Flattening creates a new array; original arrays stay unchanged.