Course contentsShow
← JavaScript
Lesson 867 of 2,72320. Array Iteration and TransformationFree lesson

Counting Occurrences with Reduce

Build a frequency map that counts how many times each element appears in an array using reduce as an accumulator.

Counting Occurrences with Reduce

You'll learn how to build a frequency map that counts how many times each element appears in an array using reduce.

The Core Idea

Imagine you have a bag of colored marbles and want to count how many of each color you have. You'd start with an empty tally sheet (an object), then pick up each marble one by one, check its color, and add a tick mark next to that color. reduce works exactly the same way for counting array elements.

Building a Frequency Map

With reduce, your accumulator is an object that stores counts. For each element you encounter, you either:

  1. Create a new entry with count 1 (first time seeing this element)
  2. Increment an existing count (seen it before)

Here's the pattern:

const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];

const counts = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});

console.log(counts);
// { apple: 3, banana: 2, orange: 1 }

The trick is (acc[fruit] || 0) + 1: if the property doesn't exist yet, it's undefined, which is falsy, so we get 0 + 1. If it exists, we get its current value plus one.

With Numbers

const numbers = [5, 2, 5, 8, 2, 5, 3];

const frequency = numbers.reduce((acc, num) => {
  acc[num] = (acc[num] || 0) + 1;
  return acc;
}, {});

console.log(frequency);
// { 2: 2, 3: 1, 5: 3, 8: 1 }

Key Takeaway: Use reduce with an empty object as the initial value to count occurrences—increment each element's property, starting from 0 if it doesn't exist yet.