Progressive Full Stack Application Development with Live Projects

JavaScript Assignment

Flatten a nested array calculating max, min, and sum

				
					const arr = [2, 3, 5, [7, 9, 11, [13, 19]], 21, [29, [31, [35]]]];

function flatten(input) {
    let flattenedArr = [];
    let max = 0;
    let min = 0;
    let sum = 0;

    // Recursive function to flatten the array and compute max, min, sum
    const doFlat = (array) => {
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            if (Array.isArray(element)) {
                doFlat(element); // Recursively flatten nested arrays
            } else {
                flattenedArr.push(element);
                sum += element; // Add to sum
                if (element > max) max = element; // Update max
                if (element < min) min = element; // Update min
            }
        }
    };

    doFlat(input); // Start flattening

    return {
        flattenedArr,
        max,
        min,
        sum
    };
}

console.log("Flatten Array using Utility => ", arr.flat(3)); // Using built-in flat method
console.log("Flattened Array and Stats => ", flatten(arr)); // Custom flatten function with stats