JavaScript reduce() Practice: Count Items by Status

Dashboards often show how many items are paid, pending or shipped. The usual technique is to build a lookup object while looping once over the data. This exercise uses reduce to turn a list of order records into a count for each status.

Before you start: Objects, bracket notation and the reduce method.

Your task

Use reduce to build an object that counts how many orders have each status. Print the paid, pending and shipped counts separated by spaces.

Starter code

const orders = [
  { id: 1, status: "paid" },
  { id: 2, status: "pending" },
  { id: 3, status: "paid" },
  { id: 4, status: "shipped" },
  { id: 5, status: "paid" },
];

// Count how many orders have each status.

Expected result

3 1 1
Open this exercise

Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.

Need a hint?

Start reduce with an empty object. For each order, set result[order.status] to its previous value (or 0) plus one.

Show the complete solution and walkthrough
const orders = [
  { id: 1, status: "paid" },
  { id: 2, status: "pending" },
  { id: 3, status: "paid" },
  { id: 4, status: "shipped" },
  { id: 5, status: "paid" },
];

// Count how many orders have each status.
const counts = orders.reduce((result, order) => {
  result[order.status] = (result[order.status] || 0) + 1;
  return result;
}, {});
console.log(`${counts.paid} ${counts.pending} ${counts.shipped}`);
  1. Pass {} as the initial accumulator. The first time a status appears, it has no property yet.
  2. Use (result[order.status] || 0) + 1. The || 0 supplies a starting count, so you add to a number instead of undefined.
  3. Return result from every callback call. After five orders, paid is 3, pending is 1 and shipped is 1.

A common mistake

Writing result[order.status] + 1 on the first visit gives NaN, because undefined plus one is not a number. Forgetting to return the accumulator also breaks the next iteration.

Try an edge case

A status that never appears is undefined, not 0, so read it with a default when you print it. An empty array returns the empty object.

Take it one step further

Add a cancelled order and print its count. Then try counting by the first letter of each status instead.

Read the javascript tool guide