Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 854
mph85 Avatar asked Apr 05 '19 07:04

mph85


People also ask

What does the flatMap () function do?

The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1 ( arr.map(...args).flat() ), but slightly more efficient than calling those two methods separately.

What is the use of flatMap in JavaScript?

flatMap() is an inbuilt function in JavaScript that is used to flatten the input array element into a new array. This method first of all map every element with the help of mapping function, then flattens the input array element into a new array. Syntax: var A = array.

What is the difference between MAP and flatMap in JavaScript?

map() function produces one output for one input value, whereas flatMap() function produces an arbitrary no of values as output (ie zero or more than zero) for each input value.


1 Answers

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.

like image 128
Matthew Avatar answered Oct 13 '22 00:10

Matthew