Function flatMap

  • Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

    Use Array.flatMap if possible or polyfill globally:

    Array.prototype.flatMap = function(callback) {
    return flatMap(this, callback)
    }

    Type Parameters

    • T
    • U

    Parameters

    • array: T[]

      any array

    • callback: ((item, index, array) => U | readonly U[])

      A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.

        • (item, index, array): U | readonly U[]
        • Parameters

          • item: T
          • index: number
          • array: T[]

          Returns U | readonly U[]

    Returns U[]

    Example

    const arr1 = [1, 2, 3, 4]

    arr1.map(x => [x * 2])
    // [[2], [4], [6], [8]]

    flatMap(arr1, x => [x * 2])
    // [2, 4, 6, 8]

    // only one level is flattened
    flatMap(arr1, x => [[x * 2]])
    // [[2], [4], [6], [8]]

    Tutorial

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap

  • Type Parameters

    • T
    • U

    Parameters

    • array: readonly T[]
    • callback: ((item, index, array) => U | readonly U[])
        • (item, index, array): U | readonly U[]
        • Parameters

          • item: T
          • index: number
          • array: readonly T[]

          Returns U | readonly U[]

    Returns readonly U[]