DEV Community

Bibin Jaimon
Bibin Jaimon

Posted on

3 1

How to write custom array flatten method in JavaScript

const nestedArray = [1, 2, [4, [5, 6, [[9]]]]]

// Method to flat an array
function flatten(input, list = []) {
    input.forEach((item) => {
        if (Array.isArray(item)) {
            flatten(item, list)
        } else {
            list.push(item)
        }
    })
    return list
}

Enter fullscreen mode Exit fullscreen mode
// Prototype to flat an array
Array.prototype.customFlatMap = function() {
    function flatten(input, list = []) {
        input.forEach((item) => {
            if (Array.isArray(item)) {
                flatten(item, list)
            } else {
                list.push(item)
            }
        })
        return list
    }
    return flatten(this)
}

const flatArray = nestedArray.customFlatMap()

console.log({ flatArray }) // [ 1, 2, 4, 5, 6, 9 ] 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay