Search code examples
javascriptecmascript-2016

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


Solution

  • 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);