Home > Mobile >  Counting number of times value appears in an array using .forEach()
Counting number of times value appears in an array using .forEach()

Time:12-10

I am trying to count the number of sentences in an array using the .forEach iterator on an array. Each time there is a full stop ('.') or an exclamation mark ('!'), it should increment a counter by 1. I was wondering if it was possible to do this using a Javascript iterator.

The array I am filtering through is called betterWords.

The code below returns 0 for some reason and I'm not sure why.

let sentences = 0;
betterWords.forEach(word => {
  if (word === '.' || word === '!') {
     return sentences =1
  }
});
console.log(sentences)

CodePudding user response:

I gather that the OP aims to count sentences in a string by counting sentence-terminating punctuation marks like . ! ? (did I miss any?) A regex match will do it. Just count the matches.

const countPunctuation = string => {
  return (string.match(/[.!?]/g) || []).length
}

console.log(countPunctuation("This is a sentence. This is definitely a sentence! Is this a sentence?"))

CodePudding user response:

Your solution was almost correct:

const betterWords = "Hello World! This is a nice text. Awesome!"
let sentences = 0;
betterWords.split('').forEach(word => {
  if (word === '.' || word === '!') {
    return sentences  = 1
  }
});
console.log(sentences)

You can not run .forEach on strings. You can only do this on Arrays. With split('') you can transform your string to an array. "ABC" => ["A", "B", "C"]

Using Regex like @danh did is a faster way to solve this problem.

  • Related