Last modified: Jul 29, 2026

Flatten Nested Arrays JavaScript Guide

Working with nested arrays can be tricky. You often need a single, flat list of values. This guide shows you how to flatten nested arrays in JavaScript. We cover simple and deep flattening methods. Each method includes clear code examples and output.

Nested arrays are arrays inside other arrays. Flattening means converting them into a one-dimensional array. This is common when processing data from APIs or user input.

Why Flatten Nested Arrays?

Flattening simplifies data manipulation. It makes iteration easier. You can apply array methods like map() or filter() to a flat list. It also improves code readability.

Imagine you have an array of student groups. Each group is an array of names. To get all student names, you need to flatten the structure.

Method 1: Using flat() (ES2019)

The easiest way is the flat() method. It creates a new array with all sub-array elements concatenated. You can specify the depth.

By default, flat() flattens one level deep. Use Infinity to flatten all levels.

Example: Flatten a 2-level nested array.

// Nested array with one level of nesting
const nestedArray = [1, [2, 3], [4, [5, 6]]];
const flatArray = nestedArray.flat();
console.log(flatArray);
Output:
[1, 2, 3, 4, [5, 6]]

Note: The inner array [5, 6] is not flattened because we used default depth 1.

Example: Flatten completely with Infinity.

const deepArray = [1, [2, [3, [4]]]];
const fullyFlat = deepArray.flat(Infinity);
console.log(fullyFlat);
Output:
[1, 2, 3, 4]

The flat() method is clean and fast. It works in modern browsers and Node.js. For older environments, consider a polyfill.

Method 2: Using reduce() and concat()

You can flatten manually using reduce(). This approach gives you full control. It is useful when you cannot use flat().

The idea is to iterate over each element. If the element is an array, concatenate it to the accumulator. Otherwise, push the value.

// Flatten one level using reduce
const nested = [1, [2, 3], 4];
const flat = nested.reduce((acc, val) => {
  return acc.concat(val);
}, []);
console.log(flat);
Output:
[1, 2, 3, 4]

This works for one level. For deeper nesting, you need recursion.

Example: Recursive flatten with reduce().

function flattenDeep(arr) {
  return arr.reduce((acc, val) => {
    // If val is array, recurse; else concatenate
    return acc.concat(Array.isArray(val) ? flattenDeep(val) : val);
  }, []);
}

const deep = [1, [2, [3, [4]]]];
const result = flattenDeep(deep);
console.log(result);
Output:
[1, 2, 3, 4]

Important: Recursion can cause stack overflow for very deep arrays. Use with caution.

Method 3: Using Spread Operator and concat()

You can flatten one level with the spread operator. This is concise but limited to one level.

const arr = [1, [2, 3], 4];
const flat = [].concat(...arr);
console.log(flat);
Output:
[1, 2, 3, 4]

This method is simple. It works well for shallow arrays. For deeper nesting, combine with recursion.

Method 4: Using toString() and split() (Not Recommended)

You can convert an array to a string, then split it. This only works for arrays of numbers or strings. It loses data types.

const mixed = [1, [2, [3]]];
const flat = mixed.toString().split(',').map(Number);
console.log(flat);
Output:
[1, 2, 3]

This method is risky. It converts everything to strings. Avoid it for complex data.

Method 5: Using Generator Functions

Generators offer an elegant recursive solution. They yield values one by one. This is memory efficient for large arrays.

function* flattenGenerator(arr) {
  for (const item of arr) {
    if (Array.isArray(item)) {
      yield* flattenGenerator(item);
    } else {
      yield item;
    }
  }
}

const nested = [1, [2, [3, [4]]]];
const flat = [...flattenGenerator(nested)];
console.log(flat);
Output:
[1, 2, 3, 4]

Generators are powerful. They work well with for...of loops. Use them for handling large nested data.

Performance Considerations

For most cases, flat() is the fastest. It is built-in and optimized. The recursive reduce() method is slower for deep arrays. Avoid toString() for performance and correctness.

Test with your data size. For arrays with hundreds of levels, consider iterative approaches. The flat() method with Infinity is usually sufficient.

Common Pitfalls

One mistake is forgetting to handle empty arrays. Flattening an empty array returns an empty array. Another is assuming all elements are arrays. Always check with Array.isArray().

Example: Flattening an array with null values.

const withNull = [1, null, [2, null]];
const flat = withNull.flat();
console.log(flat);
Output:
[1, null, 2, null]

Null values are preserved. This may be unexpected. Filter them out if needed.

Real-World Example: Flattening API Data

Imagine an API returns user data with nested roles. You need a flat list of all roles.

const users = [
  { name: 'Alice', roles: ['admin', 'editor'] },
  { name: 'Bob', roles: ['viewer'] },
  { name: 'Charlie', roles: ['editor', 'moderator'] }
];

// Extract roles and flatten
const allRoles = users.map(user => user.roles).flat();
console.log(allRoles);
Output:
['admin', 'editor', 'viewer', 'editor', 'moderator']

This is a common pattern. You can use flatMap() for a shorter version.

const allRolesFlatMap = users.flatMap(user => user.roles);
console.log(allRolesFlatMap);
Output:
['admin', 'editor', 'viewer', 'editor', 'moderator']

flatMap() is like map() followed by flat() of depth 1. It is efficient for this use case.

Conclusion

Flattening nested arrays is a core JavaScript skill. You learned five methods: flat(), reduce() with recursion, spread operator, toString(), and generators. The flat() method is the easiest and most modern. For older browsers, use the recursive reduce() approach. Always consider performance and data type safety.

Practice with your own data. Try combining these methods with other array operations. For more on arrays, see our JavaScript Array Methods Guide and JavaScript Array Variables Guide. Happy coding!