| Viewed 31 times

Get the average length of each word in the sentence in Javascript?


Create a function that takes in a sentence and returns the average length of each word in that sentence. Round your result to two decimal places.

1 Answer
Mohammad Qandeel
Answered
0
function averageWordLength(str) {
 let arr = str.split(' ').map(x=>x.match(/\w/g).join('').length)
 return parseFloat((arr.reduce((a,b)=>a+b,0)/arr.length).toFixed(2))
} 
//Example
averageWordLength('Welcom to javasecript') // 6.33