map()

Create an Array by executing a function for each Array element.

Signature

map(function: (val: Any) => Any): Array<T>

Description

The map() method creates an Array by sequentially invoking a function on the elements of the calling array. The new Array elements are the value of function after each call. The function parameter can be an anonymous Function or a top-level object method.

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

Anonymous Function or top-level object method to invoke for each element of the calling array. The function accepts an Array element as an argument.

function parameters:

Parameter Type Required Description

val

Any

Array element to be evaluated.

Return value

Type Description

Array

Array with the result of function invoked on each element of the calling array.

Examples

  1. Create an Array by mapping Array elements to subArrays that are constructed from the element value and the element value plus one, using an anonymous Function:

    [1, 2, 3].map(x => [x, x + 1])
    [
      [
        1,
        2
      ],
      [
        2,
        3
      ],
      [
        3,
        4
      ]
    ]
  2. Create an Array by passing a top-level object method as the mapping Function:

    [{name: "D"}, {name: "E"}].map(Collection.create)
    [
      {
        name: "D",
        coll: Collection,
        ts: Time("2023-02-18T20:06:25.620Z"),
        indexes: {},
        constraints: []
      },
      {
        name: "E",
        coll: Collection,
        ts: Time("2023-02-18T20:06:25.620Z"),
        indexes: {},
        constraints: []
      }
    ]

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!