Finding average word length of sentences - JavaScript


We are required to write a JavaScript function that takes in a string of strings joined by whitespaces. The function should calculate and return the average length of all the words present in the string rounded to two decimal places

Example

Following is the code −

const str = 'This sentence will be used to calculate average word length';
const averageWordLength = str => {
   if(!str.includes(' ')){
      return str.length;
   };
   const { length: strLen } = str;
   const { length: numWords } = str.split(' ');
   const average = (strLen - numWords + 1) / numWords;
   return average.toFixed(2);
};
console.log(averageWordLength(str));
console.log(averageWordLength('test test'));

Output

Following is the output in the console −

5.00
4.00

Updated on: 18-Sep-2020

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements