Flatten

Home page

A function to flatten the nesting in an arbitrary list of values

Input is equivalent to the list below

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

Result is equivalent to the list below

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

Try out my solution below.

Iterative:
Flatten = (array) => {
    for (let i = 0; i <= array.length; i++) {
        while (true) {
            if (array[i] !== undefined && array[i].constructor === Array) {
                array.splice(i, 1, ...array[i]);
            } else 
                break;
        }
    };
    return array;
}
Iterative:
FlattenRecursive = (array) => {
    return array.reduce((accumulator, currentValue) => {
        return accumulator.concat(currentValue.constructor === Array ? Flatten(currentValue) : currentValue);
    }, []);
}
Shortest
const Flatten = t => Array.isArray(t) ? [].concat(...t.map(Flatten)) : t;
Answer: