Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript flat()

flat reduces nested arrays into a single level array.

It is useful for cleaning nested data.

Why We Need It

Nested arrays appear in grouped data, UI grids, and API responses.

flat makes that data easier to process.

Syntax

array.flat(depth)

Basic Example

1. One level

const nested = [1, [2, 3]];
const flat = nested.flat();

console.log(flat);

Default depth is 1.

Real World Example

2. Two levels

const nested = [1, [2, [3]]];
const flat = nested.flat(2);

console.log(flat);

Provide depth to flatten further.

Multiple Use Cases

Flatten Nested Arrays

flat reduces the nesting level of arrays.

By default it flattens one level.

Depth Control

Pass a depth number to flatten deeper levels.

Use Infinity to fully flatten.

Non-Mutating

flat returns a new array and does not mutate the original.

That makes it safe for immutable workflows.

More Examples

3. Infinity depth

const nested = [1, [2, [3, [4]]]];
const flat = nested.flat(Infinity);

console.log(flat);

Infinity flattens all levels.

4. Remove empty slots

const sparse = [1, , 2];
const flat = sparse.flat();

console.log(flat);

flat removes empty slots in sparse arrays.

Comparison

Without

const flat = nested.reduce((acc, arr) => acc.concat(arr), []);

With

const flat = nested.flat();

Common Mistakes and Fixes

Assuming flat mutates

flat returns a new array.

Forgetting depth

Specify depth when arrays are deeply nested.

Using flat for non-arrays

flat only works on arrays.

Interview Questions

What does flat do?

It flattens nested arrays to a given depth.

Does flat mutate?

No, it returns a new array.

How do you flatten all levels?

Use flat(Infinity).

Practice Problem

Practice: Flatten a two-level nested array.

const nested = [1, [2, 3]];
// TODO: flatten

One Possible Solution

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

Frequently Asked Questions

Does flat mutate the array?

No, it returns a new array.

What is the default depth?

1.

How do I fully flatten?

Use flat(Infinity).

Try It Yourself

Try different depths to see how arrays flatten.