The Array.flatMap Method in JavaScript

Published: Saturday, June 4, 2022

Greetings, friends! In my previous post, I discussed how to use the Array.flat method in JavaScript. In this tutorial, I will discuss the Array.flatMap method.

Similar to the flat method, the ECMAScript 2019 specification officially added the flatMap method. You can think of the flatMap method as calling the map method followed by the flat method. However, flatMap was designed to be more performant than calling these methods individually.

Let's look at an example of using map followed by flat.

javascript
Copied! ⭐️
const array = [1, 2, 3, 4, 5];

const mappedArray = array.map(num => [num * 2]);

console.log(mappedArray); // [[2], [4], [6], [8], [10]]

const flattenedMapArray = mappedArray.flat(); // defaults to a depth of one when no value is passed

console.log(flattenedMapArray); // [2, 4, 6, 8, 10]

The above code snippet is similar to the following:

javascript
Copied! ⭐️
const array = [1, 2, 3, 4, 5];

const flattenedMapArray = array.flatMap(num => [num * 2]);

console.log(flattenedMapArray); // [2, 4, 6, 8, 10]

Function Definition

According to MDN, the flatMap method can accept two parameters and returns a new array with each element being the result of the callback function. These parameters are the same as the map method. The parameter, thisArg, is a value you can use as the this context when executing callbackFn. It's also an optional parameter and less commonly used.

javascript
Copied! ⭐️
flatMap(callbackFn, thisArg)

We can expand this function definition to include the parameters of the callback function, callbackFn. The callback function can accept three parameters, which are the same as the map method.

javascript
Copied! ⭐️
flatMap((element) => { /* ... */ }, thisArg)
flatMap((element, index) => { /* ... */ }, thisArg)
flatMap((element, index, array) => { /* ... */ }, thisArg)

Check out my Array.map article to learn more about how to use each parameter inside the map method. The parameters in map behave similar to flatMap. The only difference is that the array is flattened after a "map" operation is performed.

Adding Elements to an Array

We can get clever with the flatMap method and use it to add elements to an array.

javascript
Copied! ⭐️
const result = [1, 2, 3].flatMap((element, index, array) => {
  return [element, element * 2, element * 3];
});

console.log(result); // [1, 2, 3, 2, 4, 6, 3, 6, 9]

If you wanted to see how this compares to using map and flat, please see the following code:

javascript
Copied! ⭐️
const mappedArray = [1, 2, 3].map(element => {
  return [element, element * 2, element * 3]
});

console.log(mappedArray); // [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

const flattenedMappedArray = mappedArray.flat();

console.log(flattenedMappedArray); // [1, 2, 3, 2, 4, 6, 3, 6, 9]

Removing Elements from an Array

We can use conditional logic to remove elements from an array, similar to the Array.filter method.

javascript
Copied! ⭐️
const result = [-1, 1, -2, 2, -3, 3].flatMap(element => {
  if (element < 0) return [];
  return [element];
});

console.log(result); // [1, 2, 3]

In the example above, we are returning an empty array when an element is a negative number. When the array is flattened, we won't see the empty array anymore. Below is how the code compares to using map and flat, individually.

javascript
Copied! ⭐️
const mappedArray = [-1, 1, -2, 2, -3, 3].map(element => {
  if (element < 0) return [];
  return [element];
});

console.log(mappedArray); // [[ ], [1], [ ], [2], [ ], [3]]

const flattenedMappedArray = mappedArray.flat();

console.log(flattenedMappedArray); // [1, 2, 3]

Adding, Removing, and Replacing Elements in One Iteration

We can use the flatMap method to both add and remove elements from an array, conditionally, in one iteration of the array. We can also use flatMap to replace elements in an array.

Suppose we want to replace every occurrence of a positive number with an object, and we want to remove negative numbers. Then, we want to add a special or bonus object at the end of the array. Let's see how our code might look.

javascript
Copied! ⭐️
const result = [-1, 1, -2, 2, -3, 3].flatMap((element, index, array) => {
  const isLastElement = index === array.length - 1;

  if (element > 0 && !isLastElement) return [{books: element}];

  if (element > 0 && isLastElement) {
    return [{books: element}, {bonusBooks: 4}];
  }

  return [];
});

console.log(result);
/* OUTPUT:
  [
    { books: 1 },
    { books: 2 },
    { books: 3 },
    { bonusBooks: 4 }
  ]
*/

In the example above, we are using conditional logic to transform an array of integers into an array of objects. Pretty cool! 😎

Conclusion

In this tutorial, we learned about the flatMap method. This method accepts parameters similar to the map method and returns a new array. It is a very powerful utility that you can use to add, remove, and/or replace elements of an array, all within one iteration. Next time you're filtering through an array and want to make modifications to it, think about using the flatMap function to help improve performance!

Resources