I've got an array of numbers and I'd like to display them in descending order but as a rank (1st, 2nd, 3rd, etc) instead of their number values while taking ties (equal number values) into consideration.
I've got the sorting as follows:
function mySorting(a, b) {
a = a;
b = b;
return a == b ? 0 : (b < a ? -1 : 1)
}
Which works fine with the call:
var myArray=[28,92,12,12,2];
myArray.sort(mySorting);
Can anyone point me in the right direction as to how I would then rank the values of myArray with 1st, 2nd, 3rd, etc. taking ties into account?
Thanks much in advance.
If you are using jQuery you can take advantage of 2 array methods $.inArray()
and $.grep
Create an array of the unique values to use for rank:
var ranks = $.grep(myArray, function(item, idx) {
return item != myArray[idx - 1];
}).reverse();/* your sort function is descending I added reverse to the ranks , remove if needed*/
Useage:
$.each(myArray, function(idx, item) {
var rank= $.inArray( item, ranks)+1;/* index position and add one for 1st,second etc*/
$('body').append('Rank of '+item+ ' is '+ rank+'<br>')
})
DEMO: http://jsfiddle.net/XWs5j/1/
API References:
http://api.jquery.com/jQuery.grep/
http://api.jquery.com/jQuery.inArray/
EDIT: Additional demo to create array of "ties" and modify output for values that tie
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.