Function flatten

  • Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

    Use Array.flat if possible or polyfill globally:

    Array.prototype.flat = function(depth) {
    return flatten(this, depth)
    }

    Type Parameters

    • A extends unknown[]
    • D extends number = 1

    Parameters

    • array: A
    • Optional depth: D

      The maximum recursion depth

    Returns FlatArray<A, D>[]

    Example

    flatten([1, 2, [3, 4]])
    // [1, 2, 3, 4]

    flatten([1, 2, [3, 4, [5, 6]]])
    // [1, 2, 3, 4, [5, 6]]

    flatten([1, 2, [3, 4, [5, 6]]], 2)
    // [1, 2, 3, 4, 5, 6]

    Tutorial

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

  • Type Parameters

    • A extends readonly unknown[]
    • D extends number = 1

    Parameters

    • array: A
    • Optional depth: D

    Returns readonly FlatArray<A, D>[]