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

275
Views
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 answers
Answer question

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 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!