

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Finding special kind of sentences (smooth) in JavaScript
- Finding the length of second last word in a sentence in JavaScript
- JavaScript Compare two sentences word by word and return if they are substring of each other
- Finding the length of a JavaScript object
- Finding average age from array of Objects using JavaScript
- Maximum average of a specific length of subarray in JavaScript
- Finding length of repeating decimal part in JavaScript
- Finding maximum length of common subarray in JavaScript
- Finding all valid word squares in JavaScript
- Finding average of n top marks of each student in JavaScript
- Finding sum of remaining numbers to reach target average using JavaScript
- Finding second smallest word in a string - JavaScript
- Finding shortest word in a string in JavaScript
- Finding word starting with specific letter in JavaScript
- Finding the average and display the maximum average of duplicate ids?
Advertisements