Javascript - flatMap method over array - (flatMap is not a function)
Asked Answered
M

3

19

According to the Mozilla Developer Website:

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map followed by a flat of depth 1, but flatMap is often quite useful, as merging both into one method is slightly more efficient.

Example:

let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];

const flatMap = arr.flatMap(x => x);
console.log(flatMap);

TypeError: arr.flatMap() is not a function

Why is this returning this error?

EDIT

I am running this through Atom text editor and have used HomeBrew to update it to the latest version using brew upgrade node and it is still giving me the same error.

I have also tried npm install n -g

Multifarious answered 5/4, 2019 at 7:53 Comment(5)
It' probably not supported in your browser yet. But, what's the point of using flatMap on that array?Expert
I just want to see that it works and then test other values as well.Multifarious
The documentation has a lot of examples and alternatives if it's not supported in your browserExpert
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Mallard
It's just a problem of browser compatibility as it's only supported on new browsers.Palpitant
S
29

I was getting this when testing with jest, it's because flatmap is only part of node 11 and I was using node 10.

As a workaround, I added require('core-js/stable'); in my setupTests.ts.

I presume also there are some browsers that won't have this either. As such I will also put that require line in my application imports somewhere.

Shopkeeper answered 31/5, 2020 at 22:59 Comment(0)
E
6

It seems that flatMap is not supported on your browser. Here you are a complete list of supported browsers: https://caniuse.com/#search=flatMap

If you really want to use it, here you are a polyfill that will grant support down to ES3: https://www.npmjs.com/package/array.prototype.flatmap

By the way, it is useful when applied on a multidimensional array!

Evasive answered 5/4, 2019 at 7:57 Comment(2)
Appreciate it, I'm running it on atom and believe I updated it the latest version of node, Still doesn't work.Multifarious
I would suggest to use when developing on node: github.com/creationix/nvm :)Evasive
C
2

It means you're using a web browser or other development environment that does not support Array.prototype.flatMap (currently Edge and IE have no support). CanIUse table here.

Also note that it is used primarily for multidimensional arrays (to avoid chaining map and flat, hence flatMap).

Chophouse answered 5/4, 2019 at 7:57 Comment(3)
I would just upgrade by using homebrew in my case right? brew upgrade node right?Multifarious
Even easier (don't need Homebrew) - npm install n -g (see this answer).Chophouse
Just uninstall node and reinstall it using nvm: github.com/creationix/nvmEvasive

© 2022 - 2024 — McMap. All rights reserved.