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

Array.prototype.reduce() β€” count word occurrences

πŸ“– Usage Example
const fruits = ['apple', 'banana', 'apple', 'cherry']
fruits.reduce((acc, f) => { acc[f] = (acc[f]||0)+1; return acc }, {})
// β†’ {apple:2, banana:1, cherry:1}

Use reduce() with an object accumulator to count how many times each value appears.

Building an object with reduce

reduce() can build any value β€” including objects. Use it to count how many times each string appears.

countOccurrences(['a', 'b', 'a']) // { a: 2, b: 1 }
πŸ’‘ Hints (3)
  • β€’ Use `{}` as the initial accumulator typed as `Record<string, number>`.
  • β€’ Use `acc[word] = (acc[word] ?? 0) + 1` to safely increment without checking existence first.
  • β€’ Remember to `return acc` at the end of the reducer.