Sometimes in JavaScript, we need to find not just the largest number in an array, but also:
👉 How many times the largest number appears
In this post, you’ll learn:
- How to find the largest number
- How to count its occurrences
- Two approaches:
filter()andreduce() - Step-by-step explanation
Problem Statement
Given an array:
const sampleArray = [5, 5, 2, 4, 5];
👉 Output should be:
Count of largest numbers in the array: 3
Step 1: Find the Largest Number
We use Math.max():
const largestNumber = Math.max(...sampleArray);
👉 Result:
largestNumber = 5
Method 1: Using filter() (Simple & Readable)
const sampleArray = [5, 5, 2, 4, 5];
const largestNumber = Math.max(...sampleArray);
const count = sampleArray.filter(num => num === largestNumber).length;
console.log("Count of largest numbers:", count); // 3
How It Works
filter()checks each element- Keeps only values equal to
largestNumber .lengthgives the count
Execution Flow
Array:
[5, 5, 2, 4, 5]
Filtered:
[5, 5, 5]
Count:
3
Method 2: Using reduce() (Interview Favorite)
const sampleArray = [5, 5, 2, 4, 5];
const largestNumber = Math.max(...sampleArray);
const count = sampleArray.reduce((acc, curr) => {
return acc + (curr === largestNumber ? 1 : 0);
}, 0);
console.log("Count of largest numbers:", count); // 3
How reduce() Works
acc→ accumulator (count)curr→ current element
👉 If value equals largest number → add 1
👉 Otherwise → add 0
Step-by-Step Execution
| Step | curr | Condition | acc |
|---|---|---|---|
| Start | – | – | 0 |
| 1 | 5 | true | 1 |
| 2 | 5 | true | 2 |
| 3 | 2 | false | 2 |
| 4 | 4 | false | 2 |
| 5 | 5 | true | 3 |
Edge Cases
1. Empty Array
const arr = [];
👉 Math.max(...arr) returns -Infinity
2. All Same Values
[3, 3, 3]
👉 Count = 3
filter() vs reduce()
| Feature | filter() | reduce() |
|---|---|---|
| Readability | Easy | Moderate |
| Performance | Slightly more memory | Better |
| Interview | Less preferred | Highly preferred |
Interview Tip
If asked:
“How to count occurrences of max number?”
Answer:
“First find the max using Math.max, then use filter or reduce to count occurrences.”
Real-World Use Cases
- Finding top scores
- Sales analysis
- Data analytics
- Ranking systems
Related Articles
👉 You can also check:
- How to Find Sum of Array Using reduce() in JavaScript (Step-by-Step Execution Explained)
- TypeError: Reduce of Empty Array with No Initial Value (Fix Explained)
Final Summary
- Use
Math.max()to find largest number - Use
filter()for simplicity - Use
reduce()for better control - Always handle edge cases
💡 Found this helpful? Subscribe to get simple JavaScript explanations, real-world coding p
Discover more from Learners Store
Subscribe to get the latest posts sent to your email.
