Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App

JavaScript Array flat() Method

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
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.

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:

  • Google Chrome
  • Edge 
  • Firefox
  • Opera
  • Safari

P

prerak_jain
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-array
  • JavaScript-Methods

Similar Reads

    JavaScript Array() Constructor
    The Array() constructor is used to create Array objects and the array constructor can be called with or without a new keyword, both can create a new Array.Syntax:new Array(Value1, Value2, ...);new Array(ArrayLength);Array(Value1, Value2, ...);Array(ArrayLength);Parameters: ValueN: An array initializ
    2 min read
    JavaScript Array constructor Property
    The JavaScript Array constructor property is used to return the constructor function for an array object. It only returns the reference of the function and does not return the name of the function. In JavaScript arrays, it returns the function Array(){ [native code] }.Syntax: array.constructorReturn
    2 min read
    JavaScript Array length
    JavaScript array length property is used to set or return the number of elements in an array. JavaScriptlet a = ["js", "html", "gfg"]; console.log(a.length);Output3 Setting the Length of an ArrayThe length property can also be used to set the length of an array. It allows you to truncate or extend t
    2 min read
    JavaScript Array from() Method
    The JavaScript Array from() method returns an Array object from any object with a length property or an iterable object. Syntax : Array.from(object, mapFunction, thisValue)Parameters:object: This Parameter is required to specify the object to convert to an array.mapFunction: This Parameter specifies
    3 min read
    JavaScript Array isArray() Method
    The isArray() method in JavaScript is used to determine whether a given value is an array or not. This method returns true if the argument passed is an array else it returns false.Syntax:Array.isArray(obj);Parameters:obj: This parameter holds the object that will be tested.Return value:This function
    3 min read
    JavaScript Array of() Method
    The Javascript array.of() method is an inbuilt method in JavaScript that creates a new array instance with variables present as the argument of the method.Syntax:Array.of(element0, element1, ....)Parameters: Parameters present are element0, element1, .... which are basically an element for which the
    2 min read
    Javascript Array at() Method
    The JavaScript Array at() method takes an integer value (index) as a parameter and returns the element of that index. It allows positive and negative integers. For the negative integer, it counts back from the last element in the array.Syntax:at(index);Parameter: This method accepts one parameter th
    3 min read
    JavaScript Array concat() Method
    The concat() method concatenates (joins) two or more arrays. It returns a new array, containing the joined arrays. This method is useful for combining arrays without modifying the originals.Syntax:let newArray1 = oldArray.concat()let newArray2 = oldArray.concat(value0)let newArray3 = oldArray.concat
    3 min read
    JavaScript Array copyWithin() Method
    The Javascript Array.copyWithin() method considers an array first and then copies part of an array to the same array itself and returns it, without modifying its size but yet the modified data whatever user wishes to have in another's place i.e, copies array element of an array within the same array
    3 min read
    JavaScript Array entries() Method
    The entries() method in JavaScript is used to create an iterator that returns key/value pairs for each index in the array.It allows iterating over arrays and accessing both the index and value of each element sequentially.Syntax:array.entries()Parameters:This method does not accept any parameters.Re
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences