JS Built-ins
← Array149 / 226
ArrayArray.prototype.reduceintermediate

Array.prototype.reduce() β€” flatten nested arrays

πŸ“– Usage Example
const nested = [[1, 2], [3, 4], [5]]
nested.reduce((acc, arr) => acc.concat(arr), [])
// β†’ [1, 2, 3, 4, 5]

Use reduce() to flatten one level of nested arrays by concatenating each sub-array.

Flattening with reduce + concat

You can flatten a 2D array using reduce() with concat().

[[1, 2], [3, 4]].reduce((acc, cur) => acc.concat(cur), []) // [1, 2, 3, 4]
πŸ’‘ Hints (3)
  • β€’ Start with `[]` as the initial accumulator.
  • β€’ Use `acc.concat(cur)` to merge each sub-array into the accumulator.
  • β€’ TypeScript needs `[] as number[]` or `<number[]>[]` for the initial value.