Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda