Open In App

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

Last Updated : 28 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to merge/flat an array of arrays in JavaScript. To do this, first, we create an array of arrays and apply some functions to flat the merged array.

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

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.

Example:

Javascript




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


Output

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

Method 2: Using Spread Operator

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

Example:

Javascript




const arr = [[1], [2, 3], [4], ["GFG"]];
const flattened = [].concat(...arr);
console.log(flattened);


Output

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

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.

For installing Underscore.js, use the below command:

npm install underscore

Javascript




const _ = require('underscore');
console.log(_.flatten([1, [2], [3, [4, [5, [6, [7]]]]]]));


Output:

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads