DEV Community

Katherine Kelly
Katherine Kelly

Posted on

JavaScript .flatMap()

In my previous post, I wrote about Celebrating JavaScript .flat() and how to flatten arrays, giving a lot of love to flat(). I naturally wanted to follow it up with a post about flatMap() and look at how it works and what it does.

flatMap()

The flatMap() method is a super merger of flat() and map().

Although based on the order of operations maybe it should be called mapFlat() 🤔.

flatMap() goes through each element using a mapping function first before the returned result is flattened into a new array of depth one. It's just like using map() followed by flat() with a depth of 1, but is slightly more efficient (an excellent 2-for-1 method).

As flatMap() only flattens 1 level, if you need to flatten beyond 1 level, you can separately call map() then flat() on your array.

Syntax

arr.flatMap(function callback(currentValue[, index[, array]]) { // do work and return element for newArray } 

The callback function for flatMap() takes three arguments:

  • currentValue: the current element being processed
  • index (optional): the index of the currentValue
  • array (optional): the array map() was called upon
const arr = ['take me out', '', 'to the ball', 'game']; arr.flatMap(a => a.split(' ')); // ["take", "me", "out", "", "to", "the", "ball", "game"] 

Using flatMap() is useful when you want to add and remove items during a map(), as it can map many to many items by handling each input item separately, versus map() itself that is always one-to-one. This means the resulting array can grow during the mapping, and it will be flattened afterward.

MDN web docs has a great example below that highlights how flatMap() works to add and remove elements.

// Let's say we want to remove all the negative numbers and // split the odd numbers into an even number and a 1 let a = [5, 4, -3, 20, 17, -33, -4, 18] // |\ \ x | | \ x x | // *[4,1, 4, [], 20, 16, 1, [], [], 18]  // *this line helps to visualize what the array will look  // like during mapping, with negative numbers represented as empty []  a.flatMap( (n) => (n < 0) ? [] : (n % 2 == 0) ? [n] : [n-1, 1] ) // [4, 1, 4, 20, 16, 1, 18] 

flatMap() is yet another useful addition to the JavaScript Array toolbox and I’ll be using this when I need to going forward. Happy coding!

Resources
Array.prototype.flatMap()

Top comments (0)