Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

229
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda