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

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

If you're seeing the error "TypeError: flat is not a function", then it could mean that:

Method Is Not Supported

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, it could be that the method is not implemented/supported by the browser version (or the Node.js version) that you're using.

To fix this, 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 flat 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.

Method Does Not Exist

It could be that you're calling the Array.prototype.flat() method on an object that is not an array. This could happen, for example, if your variable can potentially have mixed types, or if you've made a mistake. In either case, you can make sure that the object you're calling the flat() method on supports it:

  • You can check if the object you're calling the flat() method on is indeed an array by using the Array.isArray() method, or;
  • You can use optional chaining when calling the flat() method — this would return undefined if the method does not exist on the object.

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