📘arr.flatMap()

JSobjectbuilt-inarraymethod ⟩ .flatMap()

arr.flatMap(f) is the same as arr.map(f).flat().

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

flatMap() allows each element to map to any number of elements.

// ⭐ "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]

Last updated