Flattening a deeply nested array of literals in JavaScript

We are required to write a JavaScript function that takes in a nested array of literals as the only argument. The function should construct a new array that contains all the literal elements present in the input array but without nesting.

For example ?

If the input array is ?

const arr = [
    1, 3, [5, 6, [7, [6, 5], 4], 3], [4]
];

Then the output array should be ?

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

Method 1: Recursive Approach

The recursive approach checks each element and recursively flattens nested arrays:

const arr = [
    1, 3, [5, 6, [7, [6, 5], 4], 3], [4]
];

const flattenArray = (arr = []) => {
    const res = [];
    for(let i = 0; i 

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

Method 2: Using Array.flat()

The built-in flat() method provides a simpler solution. Use Infinity as the depth parameter to flatten all levels:

const arr = [
    1, 3, [5, 6, [7, [6, 5], 4], 3], [4]
];

const flattened = arr.flat(Infinity);
console.log(flattened);
[
    1, 3, 5, 6, 7,
    6, 5, 4, 3, 4
]

Method 3: Using toString() and split()

This approach converts the array to a string and splits it back, but only works with primitive values:

const arr = [
    1, 3, [5, 6, [7, [6, 5], 4], 3], [4]
];

const flattened = arr.toString().split(',').map(Number);
console.log(flattened);
[
    1, 3, 5, 6, 7,
    6, 5, 4, 3, 4
]

Comparison

Method Readability Performance Browser Support
Recursive Good Moderate All browsers
Array.flat() Excellent Best ES2019+
toString/split Poor Good All browsers

Conclusion

Use Array.flat(Infinity) for modern environments as it's the cleanest solution. For older browsers or custom logic needs, implement the recursive approach.

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

417 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements