Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

255
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda