Technical skill practice
JavaScript Fold with reduce: Accumulate a Checked Summary
A fold combines elements into an accumulator; JavaScript arrays provide reduce for this task. Give the accumulator an initial value so the empty-input behavior and output shape are explicit.
The task
Summarize parcel count and total weight from fictional records. Each callback returns a new summary instead of relying on an accidental callback side effect.
Runnable Node 22 example
const assert = require('node:assert/strict');
const parcels = [{kg: 2}, {kg: 5}, {kg: 1}];
const summarize = items => items.reduce((summary, item) => ({
count: summary.count + 1,
kg: summary.kg + item.kg
}), {count: 0, kg: 0});
assert.deepEqual(summarize(parcels), {count: 3, kg: 8});
assert.deepEqual(summarize([]), {count: 0, kg: 0});
assert.throws(() => [].reduce((a, b) => a + b), TypeError);
console.log(JSON.stringify(summarize(parcels)));
Expected output and explanation
The accumulator starts at zero parcels and zero kilograms. Each record increments the count and adds its weight. Returning the updated summary carries that value into the next callback, producing three parcels totaling eight kilograms.
The empty list returns the provided initial summary without a callback. The separate assertion demonstrates the failure of reducing an empty array without an initial value. This is one reason the initial accumulator belongs in the contract rather than being an afterthought.
Output from the example
{"count":3,"kg":8}
Pitfall to check
An omitted callback return changes the next accumulator to undefined and usually breaks the calculation. Validate units and input types before using a summary in a real workflow; this fixture contains known numeric kilogram values.
Questions, answered
Does JavaScript have a built-in Array.fold method?
Not as a standard Array method. reduce expresses the left-to-right accumulation demonstrated here, so fold and reduce queries share this tutorial.
Sources and examples
ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.
Your experience. A complete resume.
Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.
Free account required. Free-plan PDF exports include a watermark.