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

227
Views
Factorising a function by using a forEach-loop

I would like to write a shorter code for find by using .forEach but I found problems with the counting and return does not work:

function find(array, element) {
 array.forEach((_, i) => {
  if (array[i] === element) {
    return i;
  }
 })
 return "Not found";  
}

let array = [2,3,5,7,11];


function find(array, element) {
  for (let i = 0; i < array.length; i++) {
    console.log(i)
    if (array[i] === element) {
      return i;
    }
  }
  return "Not found";
}

console.log(find(array, 5)) //2
console.log(find(array, 12)) //Not found

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

let array = [2,3,5,7,11];

function find(array, element) {

let index =  array.indexOf(element) != -1 ? array.indexOf(element) : "Not Found";  

return index;

}

console.log(find(array, 5))

console.log(find(array, 12))

about 4 years ago · Juan Pablo Isaza Report

0

return is not going to work inside a forEach I suggest you use the filter function instead. but if you insist on using forEach you can use this code as a sample.

function find(array, element) {
let result="not found";
 array.forEach((arrayItem, i) => {
  if (arrayItem === element) {
    result = i;
  }
 })
 return result;  
}
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!