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

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

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 Denunciar

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 Denunciar

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