Flatten an Array in JavaScript: Use flat() to Handle Nested Arrays

JavaScript flat function

Arrays often hold other arrays. This happens with API responses, form data, or nested objects. These layers add extra steps when you want to work with the values. A flat array in JavaScript removes the inner arrays and gives you one simple list.

Let’s move on to the following section to cover everything you need to learn about how the flat() function works in JavaScript and see examples.

What Does It Mean to Flat an Array in JavaScript?

JavaScript includes a built-in method called .flat() to flatten arrays. It allows you to remove inner arrays and combine all values into one list.

Syntax:

array.flat([depth])
  • array is the original array.
  • depth is optional. It tells how deep to flatten the array.
  • The default depth is 1.

Parameters:

  • flat(1) flattens one level (default).
  • flat(2) flattens two levels.
  • flat(Infinity) flattens all nested levels.

For example:

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

Output:

 [1, 2, 3, 4, 5]

The nested array holds numbers and other arrays inside it. The flat(2) call removes two levels of nesting and returns one flat list.

Understand the Deep Flat in JavaScript

A deep flat means you want to flatten an array all the way, no matter how many nested levels it has.

To do this, pass Infinity as the depth:

const arr = [1, [2, [3, [4, 5]]]];
const deepFlat = arr.flat(Infinity);

The output:

[1, 2, 3, 4, 5]

So in this context:

  • flat() = shallow flatten (default is 1 level)
  • flat(Infinity) = deep flatten (removes all nested levels)

Use Infinity when you don’t know how many levels the nesting goes.

Browser Support and Polyfill for flat()

The Array.prototype.flat() method is supported in most modern browsers:

BrowserSupport
Chrome69+
Firefox62+
Edge79+
Safari12+
Node.js11+
Internet ExplorerNot Supported

This code adds support for .flat() in older browsers:

if (!Array.prototype.flat) {
  Array.prototype.flat = function(depth = 1) {
    return this.reduce((acc, val) => {
      if (Array.isArray(val) && depth > 0) {
        acc.push(...val.flat(depth - 1));
      } else {
        acc.push(val);
      }
      return acc;
    }, []);
  };
}

console.log([12,3,[14, [undefined, 15, [null, true]]],55,[5544]].flat(5));

The output:

[ 12, 3, 14, undefined, 15, null, true, 55, 5544 ]

It checks if .flat() exists. If not, it defines the method using reduce and recursion. Add this before you use .flat() to make sure the method works everywhere.

Examples

Nested arrays:

You can flatten nested arrays with the flat function. It works in modern browsers and takes an optional depth value.

const numbers = [10, [20, 30], [40, [50]]];
const firstLevel = numbers.flat(1);
console.log(firstLevel);  

Output:

[ 10, 20, 30, 40, [ 50 ] ]

This removes only the first layer of nesting. Deeper arrays stay as they are.

Flatten all levels:

const deepArray = [10, [20, [30, [40]]]];
const fullFlat = deepArray.flat(Infinity);
console.log(fullFlat);  

Output:

[10, 20, 30, 40]

You can pass Infinity to flatten every layer, no matter how deep.

Flatten an array with custom objects:

const data = [
  { id: 1 },
  [{ id: 2 }, { id: 3 }],
  [[{ id: 4 }], [{ id: 5 }]],
];

const flatData = data.flat(2);
console.log(flatData);

Here you have a list of objects nested in arrays. The .flat(2) call brings all objects to one level, so you can loop through them. It doesn’t need a check for depth.

Flatten deeply nested form data:

const formData = [
  ['name', 'John'],
  [['email', '[email protected]']],
  [[[['age', 30]]]],
];

const cleanData = formData.flat(Infinity);
console.log(cleanData);

Output:

[ 'name', 'John', 'email', '[email protected]', 'age', 30 ]

If form data comes in layers from a server or script, you can flatten it completely. This gives a clean list you can loop through or pair up later.

Wrapping Up

You learned what it means to flatten an array and why it’s useful for nested data. You also explored how to use the built-in .flat() method and how the depth parameter works.

Here’s a quick recap:

  • Use .flat() to turn nested arrays into a single-level array.
  • Set depth to control how many levels to flatten.
  • Use Infinity for full flattening.
  • Add a polyfill if you need support in older browsers.

Similar Reads

JavaScript Popup Boxes: How they Works with Examples

JavaScript uses popup boxes to show quick messages or ask for direct input. These boxes stop the flow of the…

JavaScript Nullish Coalescing Operator Guide with Examples

The JavaScript nullish coalescing operator (??) gives a default value when a variable is null or undefined. Understand the Nullish…

JavaScript Ninja Code for Beginners

JavaScript Ninja Code points to ways that help a person write code that runs fast and stays easy to read.…

JavaScript Math atan: Arc Tangent of a Number in Radians

Math.atan() function in JavaScript helps you to solve math problems in your code. It turns a number into an angle.…

Understanding Comments in JavaScript for Beginners

Comments in JavaScript help you explain code and prevent mixing. They guide anyone who reads or edits your script. Understand…

JavaScript Class and Object Constructors with Examples

Object constructors and class constructors in JavaScript create objects in a structured way. Both provide methods to build reusable code.…

JavaScript Loops and Iteration: How They Work with Examples

You use loops in JavaScript to repeat code without copying it many times. This helps when you handle lots of…

JavaScript Math acos Function

The Math.acos function finds the angle in radians from a cosine value in JavaScript. It gives a value between 0…

JavaScript Math sin Function with Syntax and Uses

Math.sin() in JavaScript gives the sine of a number. This number must be in radians. You use it to work…

JavaScript Math tan: The Tangent of an Angle in Radians

JavaScript Math.tan() finds the tangent of an angle in radians. You use it when you need to solve angle-based math.…

Previous Article

Print in JavaScript Console Using Log, Info, Warn, and Error

Next Article

JavaScript While Loop: How It Works with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.