JavaScript Program to Print the Frequency of Each Character in Alphabetical Order
Last Updated :
06 Nov, 2023
In this article, we are going to implement a JavaScript program to print the frequency of each character in alphabetical order. This operation involves counting how many times each character (typically, alphabetic characters) appears in a given text and then displaying the results in alphabetical order.
Example:
Input: str = “aabccccddd”
Output: a2b1c4d3
Since it is already in alphabetical order, the frequency
of the characters is returned for each character.
Input: str = “geeksforgeeks”
Output: e4f1g2k2o1r1s2
Using Regular Expression
In this approach, we are using regular expressions to remove any non-alphabetic element from the string, then storing the alphabet and their respective frequencies in an object called frequency.
Syntax:
const cleanedString = inputString.replace(/[^a-z]/gi, '').toLowerCase();
Javascript
const printAlphabeticalFrequency = (
inputString ) => {
const cleanedString = inputString
.replace(/[^a-z]/gi, "" )
.toLowerCase();
const frequency = {};
for (let char of cleanedString) {
if (!frequency[char]) {
frequency[char] = 1;}
else {
frequency[char]++;
}}
const characters =
Object.keys(frequency).sort();
for (let char of characters) {
console.log(
char + ": " +
frequency[char]
);}
};
const inputString = "Geeks for Geeks" ;
printAlphabeticalFrequency(inputString);
|
Output
e: 4
f: 1
g: 2
k: 2
o: 1
r: 1
s: 2
Using a match() Method
In this approach, we are using the match method of JavaScript. It is an inbuilt method of JavaScript to search a string for a match against any regular expression. If the match is found, then this will return the match as an array.
Syntax:
const matches = cleanedString.match(new RegExp(char, 'g'));
Javascript
const printAlphabeticalFrequency = (
inputString ) => {
const cleanedString = inputString
.replace(/[^a-z]/gi, "" )
.toLowerCase();
const alphabet =
"abcdefghijklmnopqrstuvwxyz" ;
const frequency = {};
for (let char of alphabet) {
const matches =
cleanedString.match(
new RegExp(char, "g" ));
if (matches) {
frequency[char] =
matches.length;
}}
for (let char of alphabet) {
if (
frequency[char] !==
undefined) {
console.log(
char + ": " +
frequency[char]
);
}}};
const inputString = "GeeksForGeeks" ;
printAlphabeticalFrequency(inputString);
|
Output
e: 4
f: 1
g: 2
k: 2
o: 1
r: 1
s: 2
Share your thoughts in the comments
Please Login to comment...