JavaScript Program to Calculate the Frequency of Each Word in the Given String
Given a string, our task is to calculate the Frequency of Each Word in the Given String using JavaScript.
Example:
Input:
"Beginner for Beginner is for Beginner"
Output:
"Beginner": 3 , "for": 2 , "is": 1
Below are the approaches for calculating the Frequency of Each Word in the Given String using JavaScript:
Table of Content
- Using an Object
- Using Map
Using an Object
In this approach, Split the input string into an array of words and initialize an empty object frequency to store word frequencies. Use a loop to iterate through each word in the array of words and Check if the word already exists as a key in the frequency object. If it does not exist, initialize its frequency to 0. Increment the frequency count for the current word by 1. Return the frequency object.
Example: The example below shows how to Calculate the Frequency of Each Word in the Given String.
function wordFreqObj(str) {
const words = str.split(/\s+/);
const freq = {};
words.forEach(word => {
freq[word] = (freq[word] || 0) + 1;
});
return freq;
}
const str = "Beginner for Beginner is for Beginner";
console.log(wordFreqObj(str));
Output
{ Beginner: 3, for: 2, is: 1 }
Time Complexity: O(n + m)
Space Complexity: O(n + m)
Using Map
In this approach, Split the input string into an array of words and initialize a frequency to new map to store word frequencies. Use a loop to iterate through each word and Check if the word already exists as a key in the Map frequency. If it does not exist, initialize its frequency to 0. Increment the frequency count for the current word by 1 using the set() method of Map. Return the frequency Map.
Example: The example below show how to Calculate the Frequency of Each Word in the Given String.
function wordFreqMap(str) {
const words = str.split(/\s+/);
// Create a Map to Store Word Frequencies
const freq = new Map();
// Iterate Through the Array of Words
words.forEach(word => {
freq.set(word, (freq.get(word) || 0) + 1);
});
return freq;
}
const str = "Beginner for Beginner is for Beginner";
console.log(wordFreqMap(str));
Output
Map(3) { 'Beginner' => 3, 'for' => 2, 'is' => 1 }
Time Complexity: O(n + m)
Space Complexity: O(n + m)