• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

168
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 3 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 3 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 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error