Check out v4 of the Fauna CLI
v4 of the Fauna CLI is now in beta. The new version introduces enhancements to the developer experience, including an improved authentication workflow. To get started, check out the CLI v4 quick start. |
array.flatMap()
This method operates on an array. You typically fetch documents from a collection as a set, not an Array. For the equivalent Set method, see set instance methods. For differences between Sets and Arrays, see Sets vs. Arrays. |
Description
Creates an Array by invoking a provided mapper function on each element of the calling Array and flattening the resulting Array by one level. The Array elements are passed as a parameter to the mapper function sequentially.
The calling Array isn’t changed.
Array iteration methods
FQL provides several methods for iterating over an Array.
array.forEach()
,
array.map()
, and
array.flatMap()
are similar but return
different values.
Method | Return value |
---|---|
Null. |
|
Array, flattened by one level. |
For examples, see:
Examples
array.map()
vs. array.flatMap()
array.flatMap()
is similar to
array.map()
, except
array.flatMap()
also flattens the resulting
Array by one level.
In the following example, array.map()
returns a two-dimensional Array:
// Create an Array of product names.
let products = [
"limes",
"avocados"
]
// Use `map()` to get a Set of matching `Product` collection
// documents for each name. Convert each Set to an Array.
products.map(product => {
Product.byName(product).toArray()
})
// Two-dimensional Array.
[
[
{
id: "777",
coll: Product,
ts: Time("2099-10-02T19:37:36.357Z"),
name: "limes",
description: "Conventional, 16 oz bag",
price: 299,
stock: 30,
category: Category("789")
}
],
[
{
id: "444",
coll: Product,
ts: Time("2099-10-02T19:37:36.357Z"),
name: "avocados",
description: "Conventional Hass, 4ct bag",
price: 399,
stock: 1000,
category: Category("789")
}
]
]
To flatten the result to a one-dimensional array, use
array.flatMap()
instead:
// Create an Array of product names.
let products = [
"limes",
"avocados"
]
// Use `flatMap()` to get a Set of matching `Product` collection
// documents for each name. Convert each Set to an Array.
// Then flatten the resulting Array by one level.
products.flatMap(product => {
Product.byName(product).toArray()
})
// One-dimensional Array.
[
{
id: "777",
coll: Product,
ts: Time("2099-10-02T19:37:36.357Z"),
name: "limes",
description: "Conventional, 16 oz bag",
price: 299,
stock: 30,
category: Category("789")
},
{
id: "444",
coll: Product,
ts: Time("2099-10-02T19:37:36.357Z"),
name: "avocados",
description: "Conventional Hass, 4ct bag",
price: 399,
stock: 1000,
category: Category("789")
}
]
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!