Ranking array elements

Yùz Nagami picture Yùz Nagami · Feb 12, 2013 · Viewed 28.3k times · Source

I need an algorithm to rank elements of an array in Javascript.

Example : I have an array as follows:

[79, 5, 18, 5, 32, 1, 16, 1, 82, 13]

I need to rank the entries by value. So 82 should receive rank 1, 79 rank 2 etc. If two entries have the same value they receive the same rank and the rank for a lower value is raised.

So for this array, the new ranking array would be:

[2, 7, 4, 7, 3, 9, 5, 9, 1, 6] 

How can I do this?

Answer

Denys Séguret picture Denys Séguret · Feb 12, 2013

var arr = [79, 5, 18, 5, 32, 1, 16, 1, 82, 13];
var sorted = arr.slice().sort(function(a,b){return b-a})
var ranks = arr.map(function(v){ return sorted.indexOf(v)+1 });
console.log(ranks);

Result :

[2, 7, 4, 7, 3, 9, 5, 9, 1, 6]

If you want to be compatible with old browsers, you may have to define a shim for indexOf and for map (note that if you want to do this very fast for very big arrays, you'd better use for loops and use an object as map instead of indexOf).