How to Merge/Flatten an array of arrays in JavaScript ? (original) (raw)

Last Updated : 08 Nov, 2024

**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.

To Merge or flatten array we can use array.flat() method. This method creates a new array with all sub-array elements concatenated into it.

**Syntax

array.flat();

JavaScript `

// Given a nested array let array = [10, [20, 30], [40, [50, 60]], 70];

// Flatten the array to a single level let flatArray = array.flat(Infinity);

// Display the flattened array console.log("Updated Array:", flatArray);

`

Output

Updated Array: [ 10, 20, 30, 40, 50, 60, 70 ]

Table of Content

**Using Spread Operator and array.concat() Method

The spread operator is used to expand the iterables into separate value and array concat() method is used to merge the arrays into single array.

**Syntax

const arr = [ 10, 20, 30 ];

// Separates the array values to individual elements let [first, second, third] = [...arr];

JavaScript `

// Given nested array let array = [10, [20, 30], [40, 50, 60], 70];

// Flatten the array to a single level let flatArray = [].concat(...array);

// Display the flattened array console.log("Updated Array:", flatArray);

`

Output

Updated Array: [ 10, 20, 30, 40, 50, 60, 70 ]

**Note: It only works to flaten single level of nested array.

**Using Underscore.js _.flatten() Function

**Underscore.js _.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

Or use this cdn in the script tag

JavaScript `

// Given nested array let array = [10, [20, 30], [40, [50, 60]], 70];

// Use _.flatten() to fully flatten the array let flatArray = _.flatten(array, true); // Pass true to flatten deeply

// Display the flattened array console.log("Updated Array:", flatArray);

`

**Output

Updated Array: [ 10, 20, 30, 40, 50, 60, 70 ]

Custom Recursive Approach to Flattening Array

This method involves creating a function that recursively processes each element of the array. If an element is itself an array, the function will call itself recursively to handle that nested array.

function flattenArray(arr) {

// Initialize an empty array to hold
// the flattened result
let result = [];

// Helper function to recursively flatten elements
function flatten(element) {
    if (Array.isArray(element)) {
    
        // If the element is an array, iterate
        // through its elements
        for (let i = 0; i < element.length; i++) {
            flatten(element[i]); // Recursively call flatten
        }
    } else {
    
        // If the element is not an array,
        // add it to the result array
        result.push(element);
    }
}

// Start the flattening process
flatten(arr);
return result;

}

// Given nested array let array = [10, [20, 30], [40, [50, 60]], 70];

const flatArray = flattenArray(array);

// Display the flattened array console.log("Updated Array:", flatArray);

`

Output

Updated Array: [ 10, 20, 30, 40, 50, 60, 70 ]