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
-
Economics & Finance
Frequency distribution of elements - JavaScript
We are required to write a JavaScript function that takes a string and returns an object representing the frequency distribution of each character in the string.
const str = 'This string will be used to calculate frequency distribution';
We need to return an object that represents the frequency distribution of various characters present in the string.
Example
Following is the code:
const str = 'This string will be used to calculate frequency distribution';
const frequencyDistribution = str => {
const map = {};
for(let i = 0; i < str.length; i++){
map[str[i]] = (map[str[i]] || 0) + 1;
};
return map;
};
console.log(frequencyDistribution(str));
Output
Following is the output in the console:
{
T: 1,
h: 1,
i: 6,
s: 4,
' ': 8,
t: 5,
r: 3,
n: 3,
g: 1,
w: 1,
l: 4,
b: 2,
e: 5,
u: 4,
d: 2,
o: 2,
c: 3,
a: 2,
f: 1,
q: 1,
y: 1
}
How It Works
The function iterates through each character in the string using a for loop. For each character, it either initializes the count to 1 (if the character hasn't been seen before) or increments the existing count by 1. The expression (map[str[i]] || 0) + 1 handles both cases efficiently.
Alternative Approach Using for...of Loop
const str = 'hello world';
const frequencyDistribution = str => {
const map = {};
for(const char of str){
map[char] = (map[char] || 0) + 1;
}
return map;
};
console.log(frequencyDistribution(str));
{
h: 1,
e: 1,
l: 3,
o: 2,
' ': 1,
w: 1,
r: 1,
d: 1
}
Using Array.reduce() Method
const str = 'javascript';
const frequencyDistribution = str => {
return str.split('').reduce((acc, char) => {
acc[char] = (acc[char] || 0) + 1;
return acc;
}, {});
};
console.log(frequencyDistribution(str));
{
j: 1,
a: 2,
v: 1,
s: 1,
c: 1,
r: 1,
i: 1,
p: 1,
t: 1
}
Conclusion
Character frequency distribution can be efficiently calculated using object mapping. The for loop approach is straightforward, while the reduce method provides a more functional programming style.
