LearnFrenzy
Sign in Take a free test

Array Methods · Array Methods Coding Problems · Question 5

Count occurrences with reduce in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Count how many times each status appears in a list of orders and print the counts from most to least frequent.

Solution
main.js
const statuses = ["shipped", "pending", "shipped", "cancelled", "shipped", "pending"];

const counts = statuses.reduce((acc, s) => {
  acc[s] = (acc[s] ?? 0) + 1;
  return acc;
}, {});

Object.entries(counts)
  .toSorted((a, b) => b[1] - a[1])
  .forEach(([status, n]) => console.log(`${status.padEnd(10)} ${n}`));

Output Verified by running it on Node.js

shipped    3
pending    2
cancelled  1

reduce builds a lookup object; Object.entries turns it into pairs that can be sorted by count and printed with forEach.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links