Skip to content
Advertisement

TypeError: arr1.flat is not a function JavaScript

What's wrong here ?

What’s wrong here? It’s saying array.flat is not a function.

const arr1 = [0, 1, 2, [[[3, 4]]]];
const flatArra1 = arr1.flat(5);
console.log(flatArra1)

Advertisement

Answer

Array.prototype.flat() is a relatively new feature, some environments such as Internet Explorer and Node.js < 11 will not support it.

You can use a polyfill such as core.js or even setup a transpiler, such as babel, the difference is that the former will not require you to build the code and setup an environment, but rather translate the call to incompatible features at runtime, while the latter will require you to build your JavaScript code before you run it.

To include core.js from the cdn, you can use the following html snippet, which also sets integrity, preventing someone who tampers the CDN server to pivot it and inject scripts into your web page (stored XSS):

<script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/3.16.1/minified.js" integrity="sha512-tRlNX+FOZA6//EYAIcNnQ0/Hfg3/ldVcRiYXmwEZuujWoSqDuQhibsFiT3PRids9qlfonkq68tJy/3LD26aRNw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

But, if you are not running on browser environment, you can either install babel (there are multiple resources online explaining how to do so) and configure preset-env to use core-js, the advantage of this approach is that the latest versions of babel will strip unused polyfills out of the final code, or you can manually install and import core.js, like the following:

yarn add core-js
npm i core-js

Then, optimize core-js to only use the needed polyfill by importing it directly:

import "core-js/actual/array/flat";
// If flat-map is used as well
import "core-js/actual/array/flat-map";

Please, note that these imports look different, this is because core-js is an UMD module, which define some global variables for the browser to use (if they are not avaliable), so only importing it suffices to have the feature avaliable.

Advertisement