Store count of digits in order using JavaScript

When working with strings containing digits, you often need to count how many times each digit appears. This is a common programming task that can be solved efficiently using JavaScript objects.

Suppose we have a string with digits like this:

const str = '11222233344444445666';

We need to write a JavaScript function that takes this string and returns an object representing the count of each digit in the string.

For this string, the expected output should be:

{
  "1": 2,
  "2": 4,
  "3": 3,
  "4": 7,
  "5": 1,
  "6": 3
}

Using Object Property Counting

The most straightforward approach is to iterate through each character and increment its count in an object:

const str = '11222233344444445666';

const mapString = str => {
    const map = {};
    for(let i = 0; i < str.length; i++){
        map[str[i]] = (map[str[i]] || 0) + 1;
    };
    return map;
};

console.log(mapString(str));
{ '1': 2, '2': 4, '3': 3, '4': 7, '5': 1, '6': 3 }

Using Array.reduce() Method

A more functional approach using the reduce method:

const str = '11222233344444445666';

const countDigits = str => {
    return str.split('').reduce((acc, digit) => {
        acc[digit] = (acc[digit] || 0) + 1;
        return acc;
    }, {});
};

console.log(countDigits(str));
{ '1': 2, '2': 4, '3': 3, '4': 7, '5': 1, '6': 3 }

How It Works

Both methods work on the same principle:

  • Initialize an empty object to store counts
  • Iterate through each character in the string
  • If the character exists as a key, increment its value
  • If it doesn't exist, initialize it with 1
  • The expression (map[str[i]] || 0) + 1 handles both cases efficiently

Comparison

Method Performance Readability Functional Style
for loop Faster Good No
Array.reduce() Slightly slower Good Yes

Conclusion

Both approaches effectively count digit occurrences in a string. The for loop method offers better performance, while the reduce method provides a more functional programming style. Choose based on your coding preferences and performance requirements.

Updated on: 2026-03-15T23:18:59+05:30

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements