I'm writing a function to find the 10 most common words in a string. However, when I go to sort my arr it repeats some of the words for their values of count.
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.`;
const tenMostFrequentWords = (str) => {
const regex = /\b[a-z]+\b/gi;
const arr = str.match(regex);
const set = new Set();
for (word of arr) {
const filteredArr = arr.filter(item => item == word);
set.add({word: word, count: filteredArr.length});
}
const newArr = Array.from(set);
newArr.sort((a,b) => b.count - a.count);
return newArr;
}
console.log(tenMostFrequentWords(paragraph));
Why is this happening?