Published at
Updated at
Reading time
2min

I haven't used Array.flatMap() yet, but after reading Dmitri Pavlutin's explainer post, I got super excited about the method because it can make code shorter.

Let's look at a quick numbers example: if you want to filter and map array values you'd probably approach it like the following.

// Filter out negative numbers
// Double the positive numbers
[-3, -1, 1, 3, 5]
  .filter((num) => num >= 0)
  .map((num) => num * 2);

// -> [2, 6, 10]

There's nothing particularly wrong with chaining filter and map calls, but what if I'd tell you that you can do this with a single iteration?

// Filter out negative numbers
// Double the positive numbers
[-3, -1, 1, 3, 5].flatMap((num) => {
  if (num >= 0) {
    return [num * 2];
  }
  
  return [];
});

// -> [2, 6, 10]

Similar to map(), flatMap() iterates over every element providing a callback function.

The flatMap method is identical to a map followed by a call to flat of depth 1.

The difference: the mentioned flat call enables adding and removing elements in a single array iteration. This is impossible using a "normal map loop".

The callback returns an empty array if the number is negative, leading to element removal. And otherwise, if the element is positive, the callback returns an array with the doubled value. That's the mapping to another value.

If you want to add elements, return an array with multiple values.

And to save some more characters, you could make the snippet even shorter using a ternary operator and filter and map with a sweet one-liner.

[-3, -1, 1, 3, 5]
  .flatMap((num) => (num >= 0 ? [num * 2] : []));
  
// -> [2, 6, 10]

The big question with this line is if that code is easy to read. A filter/map combination goes better with my eyes, but it's probably just a matter of time until I get used to seeing these short flatMap calls.

So, what's the browser support of flatMap, you may ask? It's pretty green and ready to use!

MDN Compat Data (source)
Browser support info for Array.prototype.flatMap()
chromechrome_androidedgefirefoxfirefox_androidsafarisafari_iossamsunginternet_androidwebview_android
6969796262121210.069

If you want to learn more about flatMap, check Dmitri's post or the flatMap MDN documentation.

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles