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

109
Views
Why does findIndex not return the first found element?

I am looking for elements in an array with findIndex.

Here is the code:

function findLower(element, index, tarray) {
  if (current_value >= element) {
    console.log("elected", element)
    return index
  }
}
const current_value = 15
const ordered_radiuses = [0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30]
const lower_index = ordered_radiuses.findIndex(findLower)
console.log("lower index", lower_index)

Which prints:

elected 0
elected 1
lower index 1

However, as 0 is lower than 15, and 0 being at index 0, I was expecting the output to be:

elected 0
lower index 0

What am I understanding wrong here ?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

See the docs:

callbackFn

A function to execute on each value in the array until the function returns true, indicating that the satisfying element was found.

You are returning index and not a boolean.

0 is a false value.

1 is a true value.

Replace return index with return true or, if you don't need the logging, replace the whole if statement with return current_value >= element

about 4 years ago · Juan Pablo Isaza Report

0

It's almost fine, but you're returning the index and it's 0 on the first loop. And as 0 is handled as false it's going to the second value of your array. So that's how it must look like:

function findLower(element, index, tarray) {
  if (current_value >= element) {
    console.log("elected", element);
    return true;
  }
}
const current_value = 15;
const ordered_radiuses = [0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30];
const lower_index = ordered_radiuses.findIndex(findLower);
console.log("lower index", lower_index);
about 4 years ago · Juan Pablo Isaza Report

0

You should pass a predicate to findIndex and should return either true or false and you are returning the index which would produce the unexpected result

function findLower(element, index, tarray) {
  return current_value >= element;
}
const current_value = 15;
const ordered_radiuses = [0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30];
const lower_index = ordered_radiuses.findIndex(findLower);
console.log("lower index", lower_index);

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!