DEV Community

Cover image for # Day 3 | How to resolve it?
Weijuer
Weijuer

Posted on

# Day 3 | How to resolve it?

The problem:
Write a function called mostFrequentWords which get the ten most frequent word from a string?

const paragraph = `I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.`

console.log(mostFrequentWords(paragraph, 3))
Enter fullscreen mode Exit fullscreen mode

and the res should be:

[
{word:'love', count:6},
{word:'you', count:5},
{word:'can', count:3},
]
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
weijuer profile image
Weijuer

So that's it.

const tenMostFrequentWords = (paragraph, num) => {
    return paragraph.match(/([\u4e00-\u9fa5]|\b\w+\b)/gi).reduce((acc, cur, index, arr) => {
        let current = acc.find(item => item.word === cur);
        if(current) {
            current.count++
        } else {
            acc.push({word: cur, count: 1});
        }
        return acc;
    }, []).sort((a, b)=> b.count - a.count).slice(0, num)
}
Enter fullscreen mode Exit fullscreen mode