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

134
Vistas
javascript : Check if there is an array member in the entered text

I have an array of words and I want to check the entered text so that if one of the array elements is in this text, it will show me that element

and in this function I want to check it:

exports.words = (text)=>{
        const words = [
                'word1' , 
                'word2' , 
                'word3' , 
                'word4'
        ];
        for (let i = 0; i < words.length; i++) {
            const el = words[i];
            if(el.includes(text)){
                return el;
            }else{
                return 'no words'
            }
        }
}

the problem is this function just return the first element (word1) And if I enter word2 or word3 in text, it returns 'no words', even though it is in the array

so how can I fix this problem?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The issue is in the else block inside the loop, the function is returning after executing the first iteration.

You should return no words from out side of the for loop which will guarantee the full loop execution if no match found:

var words = (text)=>{
  const words = ['word1','word2','word3','word4'];
  for (let i = 0; i < words.length; i++) {
      const el = words[i];
      if(el.includes(text)){
          return el;
      }      
  }
  return 'no words'; //return here
}

console.log(words('word2')); //word2
console.log(words('other')); //no words

about 4 years ago · Juan Pablo Isaza Denunciar

0

the problem is inside your for loop. You're returning 'no words' after only first item of an array checked, you're not even getting to second item.

return words.some(word => word === text) ? text : 'no words'

should do the job :)

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