Flatten one level
Turn arrays of arrays into a single-level array.
JavaScript · Function
Array.prototype.flat() creates a new array by recursively concatenating nested arrays up to a chosen depth. Without an argument, it flattens one level.
Calling flat() creates a new array by concatenating nested array elements up to the requested depth. The default depth is 1; non-array elements are copied directly, and the original array is not changed.
flat()
flat(depth)| Name | Type | Description |
|---|---|---|
depth | number (optional) | The depth level specifying how deeply nested arrays should be flattened. Defaults to 1. |
A new array with sub-array elements concatenated into it.
flat() returns a new array containing nested elements concatenated through the specified depth.flat() does not mutate the source array; it returns a new shallow-copy array.const nested = [1, [2, [3, 4]], 5];
console.log(nested.flat());
console.log(nested.flat(2));The first call flattens one nesting level; the second flattens two levels.
Turn arrays of arrays into a single-level array.
Normalize data nested at a known depth.
Process array-like objects that expose length and integer-indexed properties.
Array.prototype.flatMap()Array.prototype.map()Array.prototype.concat()Array.isArray()