The Wayback Machine - https://web.archive.org/web/20240707132040/https://www.geeksforgeeks.org/javascript-array-flat-method/
Open In App

JavaScript Array flat() Method

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Javascript arr.flat() method was introduced in ES2019. The flat() method in JavaScript creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. If no depth is provided, it defaults to 1.

Syntax:

arr.flat([depth])

Parameters

This method accepts a single parameter as mentioned above and described below:

  • depth: It specifies, how deep the nested array should be flattened. The default value is 1 if no depth value is passed as you guess it is an optional parameter.

Return value

It returns an array i.e. depth levels flatter than the original array, it removes nesting according to the depth levels.

Array flat() Method Examples

Example 1: Flattening a Multilevel Array

The code initializes a multilevel array, then applies the flat() method with Infinity parameter to recursively flatten all nested arrays into a single-level array. The result is logged.

JavaScript
// Creating multilevel array
const numbers = [['1', '2'], ['3', '4',
    ['5', ['6'], '7']]];

const flatNumbers = numbers.flat(Infinity);
console.log(flatNumbers);

Output
[
  '1', '2', '3',
  '4', '5', '6',
  '7'
]

Example 2: Flattening Nested Arrays with flat() Method

The code demonstrates flattening a nested array to different levels using the flat() method. It applies flat() with various depth parameters (0, 1, 2) to flatten nested arrays accordingly and logs the results.

JavaScript
let nestedArray = [1, [2, 3], [[]],
    [4, [5]], 6];

let zeroFlat = nestedArray.flat(0);

console.log(
    `Zero levels flattened array: ${zeroFlat}`);
// 1 is the default value even
// if no parameters are passed
let oneFlat = nestedArray.flat(1);
console.log(
    `One level flattened array: ${oneFlat}`);

let twoFlat = nestedArray.flat(2);

console.log(
    `Two level flattened array: ${twoFlat}`);

// No effect when depth is 3 or
// more since array is already
// flattened completely.
let threeFlat = nestedArray.flat(3);
console.log(
    `Three levels flattened array: ${threeFlat}`);

Output
Zero levels flattened array: 1,2,3,,4,5,6
One level flattened array: 1,2,3,,4,5,6
Two level flattened array: 1,2,3,4,5,6
Three levels flattened array: 1,2,3,4,5,6

Note: For depth greater than 2, the array remains the same, since it is already flattened completely. 

Example 3: Flattening an Array with undefined Element

This code creates an array arr with elements [1, 2, 3, empty, 4]. When flat() is called on arr, it removes the empty slot and creates a new flattened array newArr with elements [1, 2, 3, 4], which is then logged to the console.

JavaScript
let arr = [1, 2, 3, , 4];
let newArr = arr.flat();
console.log(newArr);

Output
[ 1, 2, 3, 4 ]

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers:

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.



Previous Article
Next Article

Similar Reads

Implement Custom Array Flat method in JavaScript
The flat() method in JavaScript is used to flatten nested arrays. By using that function we can directly convert any type of array into 1D array. These are the following approaches to implementing a custom array flat method in JavaScript: Table of Content Using Recursion approachUsing Iterative approachUsing Recursion approachThis approach uses a r
2 min read
Build Tree Array from Flat Array in JavaScript
To convert a flat array of comments into a tree-like structure using JavaScript. This technique is particularly useful when you need to render nested comments or any other hierarchical data in your web application. We will write a function called buildCommentsTree that takes the flat array of comments as input and returns a tree-like array of comme
7 min read
TypeScript Array flat() Method
TypeScript flat() method of Arrays allows you to create an array while preserving the one. It combines all the elements from sub-arrays, adds them to the parent array, to the specified depth, and enables you to merge a sub-array into its parent array without modifying the structure. Syntax:array.flat([depth]); Parameters:depth (optional): The depth
1 min read
How to Design Flat Shading Graphics using p5.js ?
Flat shading is a lighting technique used in 3D computer graphics to shade each polygon of an object based on the angle between the polygon's surface normal and the direction of the light source, their respective colors and the intensity of the light source. Color is computed once for each face of the polygon.All pixels in a polygon are set to the
1 min read
Onsen UI CSS Component Material Flat Button
Onsen UI CSS is used to create beautiful HTML components. It is one of the most efficient ways to create HTML5 hybrid components that are compatible with both mobile and desktop. Buttons are one of the most common UI elements. When we want to perform some action and want to navigate to a different page then we can use the button. Onsen UI CSS Compo
2 min read
How to extend an existing array with another array without creating a new array in JavaScript ?
JavaScript arrays are a powerful data structure that allows you to store and manipulate collections of data. Often, we may need to combine or extend two or more arrays into a single array. It's easy to create a new array by concatenating two or more arrays but if we want to extend an existing array without creating a new array. There are two easy w
2 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
How does Promise.all() method differs from Promise.allSettled() method in JavaScript ?
In this article, we will first understand in brief the Promise.all() as well as Promise.allSettled() methods and then we will try to visualize how they differ from each other through some theoretical as well as some coding examples. Both Promise.all() and Promise.allSettled() methods are the methods of a Promise object (which is further a JavaScrip
4 min read
How does Promise.any() method differs from Promise.race() method in JavaScript ?
In this article, we will first try to understand how we may declare or use Promise.any() and Promise.race() methods followed by some facts which will eventually help us to understand how they differ from each other (through theoretical as well as coding examples). Let us first quickly understand in brief about both the methods followed by their syn
5 min read
How toReversed() method is different from reverse() method in JavaScript
In JavaScript, reverse() and toReversed() methods do the same job as reversing but toReversed() does not change the original array. The reverse() method changes the original array. Below we have explained both methods. Table of Content Reverse() MethodtoReversed() methodReverse() MethodThe reverse() method is a built-in method for arrays in JavaScr
2 min read
three90RightbarBannerImg