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

131
Views
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 answers
Answer question

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 Report

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 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!