Inserting a space at a specific index of a string – JavaScript

By using slice() method :

Explanation :

1. s = "12:40:22AM"
2. indexPosition = 10 - 2 = 8
3. result = 12:40:22 + " " + AM = 12:40:22 AM

Finding the Count of Largest Numbers in an Array in JavaScript (Step-by-Step Guide)

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() and reduce()
  • 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
  • .length gives 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

StepcurrConditionacc
Start0
15true1
25true2
32false2
44false2
55true3

Edge Cases

1. Empty Array

const arr = [];

👉 Math.max(...arr) returns -Infinity


2. All Same Values

[3, 3, 3]

👉 Count = 3


filter() vs reduce()

Featurefilter()reduce()
ReadabilityEasyModerate
PerformanceSlightly more memoryBetter
InterviewLess preferredHighly 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:


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