Flatten Array

Flatten Array

Given a nested array, write a code to extract all the values from the display into a single-dimensional array.

//Example.
const input = [1, [2, [3, 4], 5], 6]
const output = flattenArray(input)
console.log(output) //[1, 2, 3, 4, 5, 6]

Recursive Approach

const flattenArray = (arr) => {
    let result = [];

    for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
            result = result.concat(flattenArray(arr[i]));
        } else {
            result.push(arr[i]);
        }
    }

    return result;
}

// Example usage:
const nestedArray = [1, [2, [3, 4], 5], 6];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray); //[1, 2, 3, 4, 5, 6]

Javascript Built-in Method

const flattenArray = (arr) => {
    const number_of_nested_elements = 2
    const flattenedArray = arr.flat(number_of_nested_elements);

    return flattenedArray

}

// Example usage:
var nestedArray = [1, [2, [3, 4], 5], 6];
var flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray); //[1, 2, 3, 4, 5, 6]

The only problem with the above approach is that you need to manually count the total number of nested elements, which can again take some more time.
So, I would recommend going with the first approach and i.e. the recursive approach.