# arr.flatMap()

[JS](../../../..) ⟩ [object](../../../obj) ⟩ [built-in](../..) ⟩ [array](..) ⟩ [method]() ⟩ .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](../../../../../master/ref/javascript-the-definitive-guide "mention") ⟩ 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 %}
