How to use Array Flat() Method In Javascript

We will create an array of arrays, and then use the flat() method to concatenate the sub-array elements.

Example:

Javascript
let arr = [[1], [2, 3], [4], ["GFG"]]; 

console.log(arr.flat());

Output
[ 1, 2, 3, 4, 'GFG' ]

How to Merge/Flatten an array of arrays in JavaScript ?

Merging or flattening an array of arrays in JavaScript involves combining multiple nested arrays into a single-level array. This process involves iterating through each nested array and appending its elements to a new array, resulting in a flattened structure.

We can Merge/Flatten an array of arrays in Javascript in the following ways:

Table of Content

  • Using Array Flat() Method
  • Using Spread Operator
  • Using Underscore.js _.flatten() Function

Similar Reads

Method 1: Using Array Flat() Method

We will create an array of arrays, and then use the flat() method to concatenate the sub-array elements....

Method 2: Using Spread Operator

We can also merge or flatten an array of arrays using the concat() method and the Spread Operator....

Method 3: Using Underscore.js _.flatten() Function

The _.flatten() function is an inbuilt function in the Underscore.js library of JavaScript which is used to flatten an array that is nested to some level....

Contact Us