CodePark/ problems / Array reduce
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Array and collection utilities

Array reduce

mediumabout 20 minutes in an interview

Implement a standalone reduce(arr, fn, initialValue) that behaves like Array.prototype.reduce. Don't call the built-in reduce or reduceRight.

It walks the array from left to right and keeps an accumulator, which is a running result. For each item it sets acc = fn(acc, value, index, arr). At the end it returns the final acc.

Starting value:

  • If initialValue is passed, acc starts as that value and the walk starts at index 0. Passing undefined explicitly still counts as passing a value.
  • If it's not passed, acc starts as the first item and the walk starts at the next index. A single item is returned without calling fn.
  • With no items and no initial value, throw a TypeError.

Edge cases from the spec:

  • Holes in a sparse array (indexes that were never assigned, as in [, , 3]) are skipped. They are never passed to fn and never used as the starting value. An array of only holes counts as empty.
  • The length is read once, before the walk. Items pushed onto the array during the walk are not visited.
  • If fn is not a function, throw a TypeError.
Input: reduce([1, 2, 3, 4], (sum, n) => sum + n, 10) Output: 20
Input: reduce([2, 3, 4], (acc, n) => acc * n) Output: 24starts with acc = 2, so fn runs twice
Input: reduce([], (a, b) => a + b) Output: throws TypeError