1 | initial version |
To determine word length with its frequency in JavaScript, you can follow these steps:
split()
method.Example:
const inputString = "The quick brown fox jumps over the lazy dog";
const wordsArray = inputString.split(" ");
length
property.Example:
const wordLengths = wordsArray.map(word => word.length);
reduce()
method to calculate the frequency of each word length.Example:
const wordFrequency = wordLengths.reduce((accumulator, currentValue) => {
accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
return accumulator;
}, {});
This will return an object where the keys represent the word length and the values represent the frequency of that length in the input string.
For example, in the input string "The quick brown fox jumps over the lazy dog", there are 3 words with a length of 3, 3 words with a length of 4, and so on. So the resulting wordFrequency
object would be:
{
"3": 3,
"4": 1,
"5": 2,
"6": 1,
"7": 1,
"9": 1
}