Filipe Merker - 8 months ago 32

Javascript Question

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`

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