yoonvak
yoonvak

Reputation: 323

word frequency function, how to return if there are more than 1 most used word?

Below is my current wordFrequency function.

I would like this to

  1. filter out the "the", "a", "an", "and" from the string.
  2. if there are more than one 'mostFrequent', show all of them.

But having a hard time figuring out how to do so. Any help?

export default function wordFrequency(textData) {
    const splitTextArr = textData.toLowerCase().split(" ")
    //const filterTextArr = splitTextArr.filter(word => {
    //    if (word !== "the" && "a" && "an" && "and" && "or") {

    //    }
    //})

    splitTextArr.reduce()

    let counts = {}
    let compare = 0
    let mostFrequent

    for (var i = 0, len = splitTextArr.length; i < len; i++) {
        var word = splitTextArr[i]

        if (counts[word] === undefined) {
            counts[word] = 1
        } else {
            counts[word] = counts[word] + 1
        }
        if (counts[word] > compare) {
            compare = counts[word]
            mostFrequent = splitTextArr[i]
        }
    }
    console.log("most used word", mostFrequent)
    return mostFrequent
}

Upvotes: 0

Views: 56

Answers (1)

sdotson
sdotson

Reputation: 820

You are really really close. I think if you want to be able to return more than one highest frequently used word, you'll want to update mostFrequent to be an array rather than just a string like so:

const mostFrequent = [];

Update that final if block to the following:

if (counts[word] > compare) {
  compare = counts[word];
  mostFrequent = [word];
}
if (counts[word] === compare) {
  mostFrequent.push(word);
}

Then if you are satisfied with returning mostFrequent as an array in all instances, you are done. If you want to return an array only if there is a tie, something like the following at the bottom should work:

if (mostFrequent.length > 0) {
  return mostFrequent;
}
return mostFrequent[0];

Now for filtering out those words. You are close with the filtering function that is commented out. I would modify to the following:

const bannedWords = ['the', 'a', 'an', 'and', 'or'];
const filterTextArr = splitTextArr.filter(word => {
  return !bannedWords.includes(word);
})

Upvotes: 2

Related Questions