Filipe Merker Filipe Merker - 5 months ago 15
Javascript Question

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.

Answer

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
Comments