Artboard 16light, inspiration, solution, idea, innovation,Google Sheets iconSwift icon
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.

Related Topics

Related Articles