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

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

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 Report

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