> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/builtin/arr/method/flatmap.md).

# arr.flatMap()

[JS](/web/js.md) ⟩ [object](/web/js/val/obj.md) ⟩ [built-in](/web/js/val/builtin.md) ⟩ [array](/web/js/val/builtin/arr.md) ⟩ [method](/web/js/val/builtin/arr/method.md) ⟩ .flatMap()&#x20;

{% hint style="success" %} <mark style="color:purple;">`arr.flatMap(f)`</mark> is the same as <mark style="color:yellow;">`arr.map(f).flat()`</mark>.

```javascript
['hello world', 'how are you'].flatMap(str => str.split(' ')),
// [ 'hello', 'world', 'how', 'are', 'you' ]
```

{% endhint %}

{% tabs %}
{% tab title="💈範例" %}
{% hint style="success" %} <mark style="color:purple;">**flatMap()**</mark> allows <mark style="color:yellow;">**each element**</mark> to <mark style="color:orange;">**map**</mark> to <mark style="color:yellow;">**any number of elements**</mark>.&#x20;
{% endhint %}

* replit ⟩ [arr.flatMap()](https://replit.com/@pegasusroe/arrflatMap#index.js)

```javascript
// ⭐ "flatMap" as "filter + map"
[-2, -1, 1, 2].flatMap(x => x < 0 ? [] : Math.sqrt(x)),
//       [-2, -1, 1,       2] 
// map : [[], [], 1, 1.41421] 
// flat: [        1, 1.41421]    (⭐ empty arrays flatten to nothing)

// ⭐ "flatMap" as "filter + (one-to-many) map"
[5, 4, -3, 20, 17, -33, -4, 18].flatMap(x => 
    x < 0       ? [] :    // ignore negative numbers
    x % 2 === 0 ? x  :    // keep even numbers
    [x-1, 1]              // split odd numbers
),
//       [    5, 4, -3, 20,     17, -33, -4, 18]
// map : [[4,1], 4, [], 20, [16,1],  [], [], 18]
// flat: [ 4, 1, 4,     20,  16, 1,          18]
```

{% endtab %}

{% tab title="📗 參考" %}

* [ ] [JavaScript: The Definitive Guide](/web/master/ref/javascript-the-definitive-guide.md) ⟩ 7.8.2 Flattening arrays with flat() and flatMap()&#x20;
  {% endtab %}

{% tab title="📘 手冊" %}

* [flatMap()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap)
  {% endtab %}
  {% endtabs %}
