DEV Community

loading...

Discussion on: How to flatten an array using recursion in Javascript

Collapse
merri profile image
Vesa Piittinen • Edited

The good old super compatible way to do it:

function flatten(array) {
    // only mutate what you own, thus create a new copy
    array = array.slice(0);
    for (i = 0; i < array.length; i++) {
        // Array.isArray(array[i])
        if (Object.prototype.toString.call(array[i]) === '[object Array]') {
            // replaces single item with all items from the array
            Array.prototype.splice.apply(array, [i, 1].concat(array[i--]));
        }
    }
    return array;
}
Enter fullscreen mode Exit fullscreen mode

This should work with pretty much any JavaScript engine released within last 20 years, and does it without recursion.

But as others are saying you should just use .flat() these days instead of reinventing the wheel.

Collapse
ip127001 profile image
Rohit Kumawat Author • Edited

Thanks for reading the article and for this solution 🙌. Really appreciate it.
But yeah I covered this solution because it covers recursion as well.