Merging nested arrays to form 1-d array in JavaScript

We are required to write a JavaScript function that takes in two nested arrays, arr1 and arr2, as the first and the second argument.

Our function should create and return a third array that contains all the elements of arr1 and arr2 but flattened to single dimension

For example, if the input to the function is ?

const arr1 = [
    1, [
        2, [
            4, 5, [
                6
            ]
        ]
    ]
];
const arr2 = [
    11, 12, [
        16, 18, [
            19, 21, [
                23
            ]
        ]
    ]
];

Then the output should be ?

const output = [1, 2, 4, 5, 6, 11, 12, 16, 18, 19, 21, 23];

Using Recursive Function

This method uses a recursive helper function to traverse nested arrays and collect all numeric elements.

const arr1 = [
    1, [
        2, [
            4, 5, [
                6
            ]
        ]
    ]
];
const arr2 = [
    11, 12, [
        16, 18, [
            19, 21, [
                23
            ]
        ]
    ]
];

const flattenAndMerge = (arr1 = [], arr2 = []) => {
    const res = [];

    const flatten = (arr = []) => {
        for(let i = 0; i < arr.length; i++){
            if(Array.isArray(arr[i])){
                flatten(arr[i]);
            }else if(typeof arr[i] === 'number'){
                res.push(arr[i])
            };
        };
    };
    flatten(arr1);
    flatten(arr2);
    return res;
};

console.log(flattenAndMerge(arr1, arr2));
[
    1, 2, 4, 5, 6,
    11, 12, 16, 18, 19,
    21, 23
]

Using Array.flat() Method

The modern approach uses the built-in flat() method with Infinity to flatten arrays of any depth.

const arr1 = [1, [2, [4, 5, [6]]]];
const arr2 = [11, 12, [16, 18, [19, 21, [23]]]];

const flattenAndMergeSimple = (arr1, arr2) => {
    return [...arr1.flat(Infinity), ...arr2.flat(Infinity)];
};

console.log(flattenAndMergeSimple(arr1, arr2));
[
  1,  2,  4,  5,  6,
  11, 12, 16, 18, 19,
  21, 23
]

Comparison

Method Complexity Browser Support Performance
Recursive Function More complex All browsers Good
Array.flat() Simple ES2019+ Optimized

Conclusion

Use Array.flat(Infinity) for modern applications as it's cleaner and more efficient. The recursive approach works well when you need more control or support older browsers.

Updated on: 2026-03-15T23:19:00+05:30

384 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements