DEV Community

Bibin Jaimon
Bibin Jaimon

Posted on

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)