flatMap()

Create an Array by applying a Function to each Array element, then flatten the result by one level.

Signature

flatMap(function: (element: T) => Array<U>): Array<U>

Description

The flatMap() method creates an Array by invoking function on each element of the calling Array and flattening the resulting array one level. The Array elements are passed as a parameter to function, sequentially.

The calling Array isn’t changed.

Parameters

Parameter Type Required Description

function

Function

Yes

Function to invoke for each Array element that the Array represents. Each Array element is passed to function as an argument. function must return an Array

function parameters:

Parameter Type Required Description

element

Any

Yes

Array element to evaluate.

Return value

Type Description

Array

A new Array that consists of the results of calling function on each element of the calling array. The resulting Array is flattened by one level.

Examples

Apply the arrow Function to each Array element and flatten the result:

[1, 2, 3].flatMap((val) => [val, val * 2, val * 3])
[
  1,
  2,
  3,
  2,
  4,
  6,
  3,
  6,
  9
]

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!