![]() |
VOOZH | about |
Given a string, our task is to calculate the Frequency of Each Word in the Given String using JavaScript.
Input:
"geeks for geeks is for geeks"
Output:
"geeks": 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
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.
{ geeks: 3, for: 2, is: 1 }
Time Complexity: O(n + m)
Space Complexity: O(n + m)
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.
Map(3) { 'geeks' => 3, 'for' => 2, 'is' => 1 }
Time Complexity: O(n + m)
Space Complexity: O(n + m)
In this approach, we use the reduce method to iterate through the array of words and build the frequency object. This method is a bit more functional and concise compared to using a loop.
Example:
{ geeks: 3, for: 2, is: 1 }