Ask Your Question

Revision history [back]

To determine word length with its frequency in JavaScript, you can follow these steps:

  1. Split the input string into an array of words using the split() method.

Example:

const inputString = "The quick brown fox jumps over the lazy dog";
const wordsArray = inputString.split(" ");
  1. Iterate over the words array and determine the length of each word using the length property.

Example:

const wordLengths = wordsArray.map(word => word.length);
  1. Use the 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
}