Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

264
Views
Counting number of times value appears in an array using .forEach()

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)
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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?"))

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!