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.

Iterator methods

FQL provides several methods for iterating over an array. forEach() and map() are similar but used for different purposes.

To perform writes on an array’s elements, use forEach(). forEach() doesn’t return a value.

To return a new array containing projected or transformed elements, use map(). map() can’t perform writes.

flatMap() works like map() except it flattens the resulting array by one level.

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

Array with 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!