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

148
Vistas
Using JavaScript count the number of elements equal to or higher than the index in a loop

I'm working on a JavaScript function that can create an authors- H-Index. H-Index is the highest number of publication an author has written with just as many citations in other articles. I have

let array = [0,0,0,1,1,2,3,3,5,6,6,7,20,20,20]

This is the number of citied articles in ascending order

I need to loop the array until the index is more that the count of the items equal to or higher than the index

Such as

for (let i = 1; i < array.length; i++){
  count all items that are above i (0's get skipped)
  if there are more than i then loop to next i if not exit with i - 1
  console.log(i)
 }

What I'm looking for is 6 with an efficient loop. Thanks for the help

I've played with map and filtered inside the loop but I can't seem to get the correct syntax

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

0

You could reverse the array or sort descending, and find the index where the index (plus one) is greater than the value.

const
    values = [0, 0, 0, 1, 1, 2, 3, 3, 5, 6, 6, 7, 20, 20, 20],
    hIndex = [...values].reverse().findIndex((v, i) => v < i + 1);

console.log(hIndex);

Approach without reversing. Kodos to Jonas Wilms.

const
    values = [0, 0, 0, 1, 1, 2, 3, 3, 5, 6, 6, 7, 20, 20, 20],
    length = values.length,
    hIndex = length - values.findIndex((v, i) => v >= length - i);

console.log(hIndex);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Maybe not the most efficient way, but it can be done with filter.

First, arrays are declared with square braces [], not curly braces {}. So, it would be:

let array = [0,0,0,1,1,2,3,3,5,6,6,7,20,20,20]

And the operation you ask for would be:

array
   .filter((element, index) => element >= index)
   .length

The callback that filter accepts can support 3 arguments:

  1. The element
  2. The index
  3. The array

Documentation can be found here.

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