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

273
Vistas
How to work around findIndex returning 0 when values are undefined?

Ran into this for the first time today.

const needle = {key1: 'value1'}
const haystack = [{key1: 'value1'}, {key2: 'value2'}]

const idx1 = haystack.findIndex((hay) => hay.key1 === needle.key1);
const idx2 = haystack.findIndex((hay) => hay.key2 === needle.key1);
const idx3 = haystack.findIndex((hay) => hay.id === needle.id);
const idx4 = haystack.findIndex((hay) => undefined === undefined);

console.log(idx1, idx2, idx3, idx4)
// 0 -1 0 0

// ideally would return
// 0 -1 -1 0

Is there a clever way to get findIndex to return -1 in this case or do I have to put guards around it?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Thanks @Xupitan. I like your solution.

const idx = haystack.findIndex((hay) => hay.id && hay.id === needle.id);

console.log(idx)
// -1
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