Anybody review my word frequency checker in string logic is there any better way to implement this?

function getDataByInput(data) {
    if (data !== '') {
      // split data string into array
      let splitedData = data.split(' ');
      let subArrayOfWords = [];
      let resultArray = [];

      // logic to count every occurence of word
      for (let i = 0; i < splitedData.length; i++) {
        // It return a subarray of every same word
        subArrayOfWords = splitedData.filter((word) => {
          return word === splitedData[i] && word;
        });

        // At this point this code has a small bug subarrayofword had multiple occurence o same word eg: if we have a array ['enter','a','word','word'] it return subarray like this - ['enter'] ['a'] ['word','word'] ['word','word'] - cause 'word' has 2 occurence to resolve this problem I will append these array into final array
        if (resultArray.length === 0) {
          // if length is 0 mean this is a first element
          resultArray.push({
            element: subArrayOfWords[0],
            size: subArrayOfWords.length,
          });
        } else {
          // check next word is unique or not
          const word = resultArray.find((ele) => {
            return ele.element === subArrayOfWords[0];
          });

          // if this unique find method return undefined then I will push it onto my result array
          if (!word) {
            resultArray.push({
              element: subArrayOfWords[0],
              size: subArrayOfWords.length,
            });
          }

        }

        // console.log(subArrayOfWords);
      }
      setResultArray(resultArray);
    }
  }```

Hey @priyanshushrama709!

Please give more information so we can understand, what you are try to do.

I want to count all occurrence of every word in a string.

eg: “This is a string string”

ans: “This” = 1
“is” = 1
“a” = 1
“string” = 2

and I want to know is this good approach to do this or any good approach to do this?

let wordFreq = (str, wrd)=>{

  let strArr = str.toLowerCase().split(" ");

  let resArr = strArr.filter(word =>  word===wrd.toLowerCase() );

  console.log(resArr.length);

}

wordFreq('This string is a string', 'string');

You can do it like this and iterate over every word on the array this only checks for one word.

1 Like

No this is not I want check every word occurrence in string like here is 5 words and I check all 5 words one by one not 1 word like you check ‘string’

I understand that but using this as a foundation you can do the thing you want. you just need to add a for loop. Try to do it and reply back. I’ll try to help more.
Good luck!

Yeah! My code above works fine it give me all occurrence of word but I want to know is there any better way to do this.

@priyanshushrama709 I really like Map for this kind of jobs. (think of HashMap in other languages).

This combined with some functional programming can make your code pretty “reasonable”.
For example:

let s = "string is a String";

s.split(" ").reduce((a, c) => {
  let k = c.toLowerCase();
  return a.has(k) ? a.set(k, a.get(k) +1) : a.set(k, 1);
}, new Map());

// Map { 'string' => 2, 'is' => 1, 'a' => 1 }

Two things to notice: I didn’t spend a single minute thinking about proper variable names AND I convert all your words/keys to lowercase [an assumption here].

Hope it helps :sparkles:

1 Like