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
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
};
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 } Advertisements
