JavaScript Program to Count the Occurrences of Each Character
Last Updated :
20 Sep, 2023
This article will demonstrate different approaches for implementing a JavaScript program to count the occurrences of each character in a string. We will be given a string as input and we return the chars used with the number it occurred in that string.
Approaches to count the occurrences of each character
- Using JavaScript objects
- Using JavaScript map
- Using JavaScript array
In this method, we will create a JavaScript object that will store all the characters and their occurrences to accomplish the task.
Example: In this example, we will store chars and their occurrences in the result object using for loop for iteration.
Javascript
let str = 'GeeksforGeeks'
let result = {}
for (let i = 0;i< str.length;i++){
let ch = str.charAt(i)
if (!result[ch]){
result[ch] =1;
}
else {
result[ch]+=1
}
}
console.log(
"The occurrence of each letter in given string is:" ,result)
|
Output
The occurrence of each letter in given string is: { G: 2, e: 4, k: 2, s: 2, f: 1, o: 1, r: 1 }
In this method, JavaScript map is used so that we can store the result in thje form of key-value pairs where key is the chars used and value will be the number of occurrences.
Example: In this example, we will iterate the given string and store result in the form of key-value pairs.
Javascript
let str = 'GeeksforGeeks'
let result = new Map()
for (let i = 0;i< str.length;i++){
let ch = str.charAt(i)
if (!result.get(ch)) result.set(ch, 1);
else {
result.set(ch, result.get(ch) + 1);
}
}
console.log(result)
|
Output
Map(7) {
'G' => 2,
'e' => 4,
'k' => 2,
's' => 2,
'f' => 1,
'o' => 1,
'r' => 1
}
In this method, we will use JavaScript Array to get the chars and occurrences by converting the string in array and then apply JavaScript array methods.
Example: In this example, we will use array reduce to return an array that contains the chars and their occurrences.
Javascript
let str = "GeeksforGeeks" ;
let strArray = str.split( "" );
let result = strArray.reduce((chars, ch) => {
if (!chars[ch]) {
chars[ch] = 1;
} else {
chars[ch] += 1;
}
return chars;
}, []);
console.log(
"The occurrence of each letter in given string is:" , result)
|
Output
The occurrence of each letter in given string is: [
G: 2, e: 4,
k: 2, s: 2,
f: 1, o: 1,
r: 1
]
Share your thoughts in the comments
Please Login to comment...