Store count of digits in order using JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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.

Therefore, for this string, the output should be −

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

Example

Following is the code −

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

Output

This will produce the following output in console −

{ '1': 2, '2': 4, '3': 3, '4': 7, '5': 1, '6': 3 }
raja
Published on 18-Sep-2020 13:24:34
Advertisements