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

mph85
  • 1,276
  • 4
  • 19
  • 39
  • 1
    It' probably not supported in your browser yet. But, what's the point of using `flatMap` on that array? – adiga Apr 05 '19 at 07:55
  • I just want to see that it works and then test other values as well. – mph85 Apr 05 '19 at 07:56
  • [The documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) has a lot of examples and [alternatives](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap#Alternative) if it's not supported in your browser – adiga Apr 05 '19 at 07:58
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap#Alternative – Pranav C Balan Apr 05 '19 at 07:58
  • It's just a problem of [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap#Browser_compatibility) as it's only supported on new browsers. – cнŝdk Apr 05 '19 at 08:01

3 Answers3

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.

Matthew
  • 10,361
  • 5
  • 42
  • 54
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!

Michele Riva
  • 552
  • 9
  • 24
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).

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79