0

I have to display the word count next to each word.

let str = "Hello there, how are you? Can you tell me how to get to the nearest Starbucks?"
    
function countingWords(){
  if (str.length === 0){
      return null;
  }
  str = str.toLocaleLowerCase();

  str.split(" ").forEach(word => {
    console.log(word, "=", str.split(word).length-1,)
  });
  return
}
countingWords()

My output:

hello = 1
there, = 1
how = 2
are = 2
you? = 1
can = 1
you = 2
tell = 1
me = 1
how = 2
to = 2
get = 1
to = 2
the = 2
nearest = 1
starbucks? = 1

The majority of this is correct but I still get a few wrong answers like "are=2" and "the=2". Does anyone know why or how to fix?

Pawel Veselov
  • 3,996
  • 7
  • 44
  • 62
Johnny Bravo
  • 163
  • 11
  • 1
    You should simply iterate the split array and count the elements. Splitting the string by each word is both inefficient and doesn't account for partial matches (there, the), plus the issue of punctuation `there,` vs `there`. – pilchard Jun 19 '21 at 16:10
  • One of the problem with your approach is that it doesn't protect against 'ne**are**st' and '**the**re' cases. And yes, it's both not really performant splitting the same string for each word and having those results repeated. – raina77ow Jun 19 '21 at 16:12
  • Does this answer your question? [How to count string occurrence in string?](https://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string) – pilchard Jun 19 '21 at 16:13

2 Answers2

1

you can try the filter method to count words. I think it's more readable. Thank you.

let str = "Hello there, how are you? Can you tell me how to get to the nearest Starbucks?"
    
function countingWords() {
  if (str.length === 0){
      return null;
  }
  str = str.toLocaleLowerCase();
  const arrayOfWord = str.split(" ");

  arrayOfWord.forEach(word => {
    console.log(word, "=", arrayOfWord.filter(wordToCheck => wordToCheck === word).length);
  });
  
  return null;
}

countingWords();
Showrin Barua
  • 1,737
  • 1
  • 11
  • 22
0

"are" contents in "nearest"

let str = "Hello there, how are you? Can you tell me how to get to the nearest Starbucks?"

function countingWords(){
if (str.length === 0){
    return null;
}
str = str.toLocaleLowerCase();

str.split(" ").forEach(word=>{
console.log(word, "=", str.split(' '+word+' ').length-1,)
})
return
}
countingWords()
Darth
  • 1,592
  • 10
  • 19