JS Built-ins
← Array153 / 226
ArrayArray.prototype.reduceRightintermediate

Array.prototype.reduceRight() β€” flatten from right

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

Use reduceRight() to flatten nested arrays from right to left.

Flattening with reduceRight

You can flatten a 2D array from right to left. To preserve the original element order, use cur.concat(acc) instead of acc.concat(cur).

[[1, 2], [3, 4]].reduceRight((acc, cur) => cur.concat(acc), []) // [1, 2, 3, 4]
πŸ’‘ Hints (2)
  • β€’ Use `cur.concat(acc)` (not `acc.concat(cur)`) so that right-to-left processing still yields left-to-right order.
  • β€’ Start with `[] as number[]` as the initial accumulator.