Solve - flat is not a function Error in JavaScript


Borislav Hadzhiev

Last updated: Oct 20, 2021


Check out my new book

Solve - flat is not a function Error #

The "flat is not a function" error occurs for multiple reasons:

  • Using the flat method in a browser that doesn't support it.
  • Using the flat method on a value that is not an array.

typeerror flat is not a function

Here is an example of how the error occurs.

const arr = {}; // ⛔️ TypeError: arr.flat is not a function const result = arr.flat();

We called the Array.flat() method on an object and got the error back.

To solve the "flat is not a function" error, make sure to only call the flat() method on arrays and in browsers that support it. The flat method can only be called on arrays and returns a new array with all sub-array elements concatenated into it.

const arr = ['a', 'b', ['c', 'd']]; const result = arr.flat(); // 👇️ ['a', 'b', 'c', 'd'] console.log(result)
The flat method is not supported in Internet Explorer. If you have to support the browser, you can use the combination of reduce and concat.
// ✅ Supported in Internet Explorer const arr = ['a', 'b', ['c', 'd']]; const result = arr.reduce((acc, val) => acc.concat(val), []); // 👇️ ['a', 'b', 'c', 'd'] console.log(result);
However, note that when it comes to large arrays (thousands of values), calling the two functions is a bit slower than using flat directly.

You can conditionally check if the value is an array by using the Array.isArray method.

const arr = null; const result = Array.isArray(arr) ? arr.flat() : []; console.log(result); // 👉️ []

We used a ternary operator, which is very similar to an if/else statement.

If the value is an array, we return the result of calling the flat method on it, otherwise we return an empty array. This way, you won't get an error, even if the value is not an array.

If the value is fetched from a remote server, make sure it is of the type you expect it to be by logging it to the console and make sure you have parsed it to a native JavaScript array before calling the flat method on it.

If you have an array-like object which you're trying to convert to an array before calling the flat method, use the Array.from method.

const set = new Set(['a', 'b', ['c', 'd']]); const result = Array.from(set).flat(); console.log(result); // 👉️ ['a', 'b', 'c', 'd']

Before calling the flat method, we convert the value to an array.

You could also use the spread syntax (...) to achieve the same result.

const set = new Set(['a', 'b', ['c', 'd']]); const result = [...set].flat(); console.log(result); // 👉️ ['a', 'b', 'c', 'd']

If the error persists, console.log the value you're calling the flat method on and make sure it's an array.

Use the search field on my Home Page to filter through my more than 3,000 articles.