Constructing an object from repetitive numeral string in 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.

So, for this string, the output should be −

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

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

{ '1': 2, '2': 4, '3': 3, '4': 7, '5': 1, '6': 3 }
raja
Published on 21-Oct-2020 11:58:04
Advertisements