Store count of integers in order using JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have a long string that represents a number like this −

const str = '11222233344444445666';

We are required to write a JavaScript function that takes in one such string. Our function is supposed to return an object that should assign a unique "id" property to each unique number in the string and one other property "count" that stores the count of the number of times the number appears in the string.

Therefore, for the above string, the output should look like −

const output = {
   '1': { id: '1', displayed: 2 },
   '2': { id: '2', displayed: 4 },
   '3': { id: '3', displayed: 3 },
   '4': { id: '4', displayed: 7 },
   '5': { id: '5', displayed: 1 },
   '6': { id: '6', displayed: 3 }
};

Example

The code for this will be −

const str = '11222233344444445666';
const countNumberFrequency = str => {
   const map = {};
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(map.hasOwnProperty(el)){
         map[el]['displayed']++;
      }else{
         map[el] = {
            id: el,
            displayed: 1
         };
      };
   };
   return map;
};
console.log(countNumberFrequency(str));

Output

And the output in the console will be −

{
   '1': { id: '1', displayed: 2 },
   '2': { id: '2', displayed: 4 },
   '3': { id: '3', displayed: 3 },
   '4': { id: '4', displayed: 7 },
   '5': { id: '5', displayed: 1 },
   '6': { id: '6', displayed: 3 }
}
raja
Published on 21-Nov-2020 09:31:42
Advertisements