Javascript Fundamentals · Array Methods

Fold a list into one value

reduce

Fold a list into one value

You have a list of line items and you want one number at the end: the total. You could keep a running sum in a variable and loop, but the list is a single value in disguise, and you want it out.

That fold is reduce. It walks the elements left to right, carrying a running value — the accumulator — and calls a reducer to combine the accumulator with each element. The final accumulator is the result.

const records = [{ amount: 5 }, { amount: 10 }, { amount: 20 }];

const total = records.reduce((sum, record) => sum + record.amount, 0);
// 35

The second argument to reduce is the seed — the accumulator's starting value. Each step hands the reducer the accumulator and the current element, then stores the reducer's return value back into the accumulator, so the next step sees the updated total.

The pitfall: seeding matters. Pass an explicit seed (0 for a sum, '' for a string, [] for a list) so the reducer always has the right shape to combine with. With an empty array and a seed, reduce returns the seed untouched — which is why 0 is the safe start for a sum.

Export totalByKey from index.js. Given a list of records and a field name, return the sum of that field across every record, starting from 0.

Challenge

You have a list of records and you need one number out of it: the total of a field. A hand-written loop starts with a guess at the seed and is easy to get wrong on an empty list. Export a totalByKey function from index.js to fold the list down.

totalByKey takes an array of records and a field name, and returns the sum of that field across every record, starting from a seed of 0. An empty array returns 0.

index.js
export function totalByKey(_records, _key) {
  return 0;
}

export function render(mount) {
  const records = [{ amount: 5 }, { amount: 10 }, { amount: 20 }];
  const total = totalByKey(records, 'amount');

  mount.textContent = `Total: ${total}`;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.