简体   繁体   中英

How to get the “rank” of a Array entry by it's value?

Suppose I have the following structure

var Arr = [
  {value: 2},
  {value: 4},
  {value: 1}
]

Ok, now i want to "rank" this values by giving them a score of 0 -> n (the array size is variable) where the biggest value receive the lowest score (0) and the lowest value receives the biggest score (n).

  • This logic just need to work with positive integers and zero.

My idea is the create a function that returns the score by the array index

getScore(Arr[0]); // 1
getScore(Arr[1]); // 0
getScore(Arr[2]); // 2

But i'm really stuck and have no idea on how to do this.

Run a sort function - then just take the index of each position as it's rank:

function getScore(array, val) {
    return array.sort(function(a, b) {
        return b.value - a.value;
    }).map(function(item) { 
        return item.value;
    }).indexOf(val);
}

getScore(Arr, Arr[0].value) //1

The 'rank' function you describe is equivalent to asking "how many entries in this array are greater than a given value?"

Here's an alternate implementation that takes the approach of simply counting:

 function getScore(array, val) { var score=0; for(var i=0; i<array.length; i++) if (array[i].value > val) score++; return score; } var Arr = [ {value: 2}, {value: 4}, {value: 1} ] console.log('getScore(Arr, Arr[0].value) →', getScore(Arr, Arr[0].value)); console.log('getScore(Arr, Arr[1].value) →', getScore(Arr, Arr[1].value)); console.log('getScore(Arr, Arr[2].value) →', getScore(Arr, Arr[2].value)); 

This will be bit faster for large arrays because it doesn't have to sort the array, and it will be more compatible with older browsers that don't support the map function. The only difference between this implementation and tymeJV's is how it will handle values that are not present in the original array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM