Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

62
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

7 months 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))

7 months 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;  
}
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs