JavaScript Array flatMap() Tutorial

In this section, we will learn what the flatMap() method is and how we can use it in JavaScript.

Note: In this section, we’re assuming you’re familiar with the `map()` and `flat()` methods.

JavaScript Arrays flatMap() Method

The `flatMap()` method is just like `flat()` except that it passes each value through a mapping function before flattening the result, and only is capable of flattening a two-dimensional array.

Basically, it’s like first calling the `map()` method on an array and then call the `flat()` method on the result array.

The `arr.flatMap(f)` is functionally equivalent to `arr.map(f).flat()`.

Array flatMap() Syntax:

array.flatMap(function(currentValue, index, arr), thisValue)

Array flatMap() Method Parameters:

The `find()` method takes two arguments.

The first argument is a reference to a function. For each element in the target array, the flatMap() method will call the reference function and pass an element to be mapped in the target reference function.

This function takes 3 arguments:

  • The first argument is the element in the array.
  • The second argument is the index of that element.
  • The third argument is a reference to the target array.

Inside this function, we specify a set of instructions that will be executed for each element in the array. These instructions are mainly related to mapping the target element to produce a new one and return that as a result.

Other than the function, the `flatMap()` method takes a second argument as well. This second argument, which is optional, is a reference to an object that will bind to the `this` keyword in the target function that we passed as the first argument.

Array flatMap() Method Return Value:

The method doesn’t change the original array and instead it’ll return a single-dimensional array with the values of the target multidimensional array all mapped and set as its elements.

Example: using Array flatMap() method in JavaScript

const arr = [1,2,3,4,5,6,7,8,9];

const flatten = arr.flatMap(value=>[value, value*10]);

console.log(flatten);

Output:

[1, 10, 2, 20, 3, 30, 4, 40, 5, 50, 6, 60, 7, 70, 8, 80, 9, 90]
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies