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
Take a look at this function it will help you to get the average length of each word in the sentence in Javascript
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
answer Link