How to Fix "flat is not a function" JavaScript Error?

Learn how to fix the "flat() is not a function" JavaScript error

Why Does This Happen?

Array.prototype.flat() method was added in ES10, and implemented in V8 v6.9 (which is used by some browsers, as well as Node.js). Therefore, if you're seeing the error "TypeError: flat is not a function", it is likely due to the method not implemented/supported by the browser version (or the Node.js version) that you're using.

How to Fix the Issue?

As a substitute for Array.prototype.flat(), you can either use a polyfill or one of the following alternatives:

Flatten Array Recursively Using a Stack

// ES5+
function flatDeep(array, depth = 1, stack = []) {
    for (const item of array) {
        if (Array.isArray(item) && depth > 0) {
            flatDeep(item, depth - 1, stack);
        } else {
            stack.push(item);
        }
    }

    return stack;
}

console.log(flatDeep([1, 2, [3, 4, [5, 6]]])); // [1, 2, 3, 4, [5, 6]]
console.log(flatDeep([1, 2, [3, 4, [5, 6]]], Infinity)); // [1, 2, 3, 4, 5, 6]

Flatten Array Recursively Using a Generator Function

Using a generator, the flatten function would be more memory efficient:

// ES6+
function flatDeep(array, depth = 1) {
    function* flatten(array, depth) {
        for (const item of array) {
            if (Array.isArray(item) && depth > 0) {
                yield* flatten(item, depth - 1);
            } else {
                yield item;
            }
        }
    }

    return [...flatten(array, depth)];
}

console.log(flatDeep([1, 2, [3, 4, [5, 6]]])); // [1, 2, 3, 4, [5, 6]]
console.log(flatDeep([1, 2, [3, 4, [5, 6]]], Infinity)); // [1, 2, 3, 4, 5, 6]

Flatten Array Recursively Using Array.prototype.reduce()

// ES6+
function flatDeep(arr, depth = 1) {
    if (depth <= 0) {
        return arr.slice();
    }

    return arr.reduce((acc, val) => acc.concat(
        Array.isArray(val) ? flatDeep(val, depth - 1) : val
    ), []);
}

console.log(flatDeep([1, 2, [3, 4, [5, 6]]])); // [1, 2, 3, 4, [5, 6]]
console.log(flatDeep([1, 2, [3, 4, [5, 6]]], Infinity)); // [1, 2, 3, 4, 5, 6]

You can rewrite the callback to Array.prototype.reduce() without arrow function to make it compatible with ES5.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.