JavaScript array.flatmap ()

We’ve already talked about array.flat (). Now flatMap, a method that combines the map() and flat() methods — mapping an array and then flattening the resulting array.

const foods = ['🍫'.'🍦' ]


// ❌ map + flat
foods.map(food => [food, '😋']. Flat () // ✅ flatMap foods. FlatMap (food => [food,'😋'] // result // ['🍫'.'😋'.'🍦'.'😋']
Copy the code

How flapMap() works

I’m going to walk you through how flapMap() works step by step. When I first learned it, IT was a bit confusing. Because I think of it as flatten and then mapping. But instead of 🙅, it’s map() and then flat().

const names = ['jane'.'john' ];

// Step 1: map
const nestedArray = names.map((name, index) => [name, index]);
// [ ['jane', 1], ['john', 2]]Copy the code

OK, we now have a nested array. And then you can flatten it with flat().

const nestedArray =  [ ['jane', 1], ['john', 2 ] ] nestedArray.flat(); / / /'jane', 1, 'john', 2]Copy the code

Of course, why don’t we just call it flatMap(). Look at 👀

const names = ['jane'.'john']; const result = names.flatMap((name, index) => [name, index]); / / /'jane', 1, 'john', 2]Copy the code

Look! The result is the same 👍

The flatMap flattens only one layer deep

When we use flat(), we know that it can receive a depth that represents flat depth. That is, we can flatten the array to the depth we want.

const depth1 = [ [1], [2] ]; depth1.flat(); / / equivalent to the depth. Flat (1) / / [1, 2] const depth2 = [[[1, 2]]]. depth2.flat(2); / / [1, 2]Copy the code

For flatMap, this is not possible, we can only flatten one layer.

const names = ['jane'];

names.flatMap((name, index) => [ [name, index] ]);
//  [ ['jane', 1]]Copy the code

Let’s break down the code logic above into two steps and see what we can see.

const names = ['jane']; Const twoLevelDeep = names.map((name, index) => [[name, index]]); [[[/ /'jane', 1]] // Step 2: flat to twoLevelDeep (); / / [['jane', 1]]Copy the code

Of course, if we do it separately, we can specify the flat depth in the second step, through depth.

twoLevelDeep.flat(2); / / /'jane', 0, 'john', 1]Copy the code

Therefore, if you want to flatten an array with more than one layer, it is best not to use the flatMap() method and break it down into two steps.

Filter with flapMap

Surprisingly, you can use flapMap to implement filtering! In the following example, we remove all negative numbers from the array.

const numbers = [1, 2, -3, -4, 5];

numbers.flatMap(number => {
  return number < 0 ? [] : [number]
})

// [ 1, 2, 5]
Copy the code

Cool! This behaves a little bit like a filter. But what’s the trick? Empty arrays.

const emptyNestedArray = [ [], 1 ]; emptyNestedArray.flat(); / / [1]Copy the code

When you try to flatten an empty array, it will be deleted. Therefore, you can use this knowledge to make flapMap behave like a filter. Severe 👍

resources

  • TC39: flatMap
  • MDN Web Docs: flatMap
  • SamanthaMing.com: Array.flat()

(after)