Constructing an object from repetitive numeral string in JavaScript

Suppose, we have a string with digits like this ?

const str = '11222233344444445666';

We are required to write a JavaScript function that takes in this string and returns an object that represents the count of each number in the string.

So, for this string, the output should be ?

const output = {
  "1": 2,
  "2": 4,
  "3": 3,
  "4": 7,
  "5": 1,
  "6": 3
};

Using a for Loop

The most straightforward approach is to iterate through each character and count occurrences:

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()

We can achieve the same result using the reduce method for a more functional approach:

const str = '11222233344444445666';

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

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

Using for...of Loop

A cleaner alternative using the for...of syntax:

const str = '11222233344444445666';

const mapStringForOf = str => {
    const map = {};
    for(const char of str) {
        map[char] = (map[char] || 0) + 1;
    }
    return map;
};

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

How It Works

All methods follow the same logic:

  • Initialize an empty object to store counts
  • Iterate through each character in the string
  • Use (map[char] || 0) + 1 to handle undefined values and increment counts
  • Return the final count object

Conclusion

These approaches effectively convert a repetitive numeral string into a frequency count object. The for...of loop provides the cleanest syntax, while reduce offers a functional programming style.

Updated on: 2026-03-15T23:19:00+05:30

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements