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?
The rank of an array is the number of dimensions it has. A scalar is considered to have rank zero.
The rank 2 array has 3 rows and 5 columns, so its shapes is (3, 5). By convention, we take the matrix shape to be rows first, then columns. The rank 3 array has 4 planes, each containing 3 rows and 5 columns, so its shapes is (4, 3, 5).
Rank of the array is the number of singular values of the array that are greater than tol. Input vector or stack of matrices. Threshold below which SVD values are considered zero. If tol is None, and S is an array with singular values for M, and eps is the epsilon value for datatype of S , then tol is set to S.
Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Property Value: It returns the rank (number of dimensions) of the Array of type System. Int32.
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
).
This won't work with older browsers because it uses ECMAScript 5 features, but it allows you to quickly and succinctly produce an array of rankings even for very large arrays. (It doesn't use indexOf
which does a linear search and thus can be slow for large arrays.)
function cmp_rnum(a,b) { // comparison function: reverse numeric order return b-a; } function index_map(acc, item, index) { // reduction function to produce a map of array items to their index acc[item] = index; return acc; } function ranks(v) { var rankindex = v.slice().sort(cmp_rnum).reduceLeft(index_map, Object.create(null)); // reduceLeft() is used so the lowest rank wins if there are duplicates // use reduce() if you want the highest rank return v.map(function(item){ return rankindex[item]+1; }); }
Example output:
> ranks([79, 5, 18, 5, 32, 1, 16, 1, 82, 13]); [2, 7, 4, 7, 3, 9, 5, 9, 1, 6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With