Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Store count of digits in order using 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.
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 } Advertisements
