I understand the JS .sort() function well enough, and I have a loose grasp on multidimensional arrays, but I’m a little stuck. Here’s what I’ve got:
var player1 = ["bob", 20];
var player2 = ["jon", 40];
var player3 = ["tim", 10];
var scores = [player1[1], player2[1], player3[1]];
scores.sort(sortfunc);
function sortfunc(a,b){
return a - b;
}
alert(scores);
Obviously this sorts the scores correctly, but what I want is to order the player names appropriately in the alert() based on their score, e.g. tim, bob, jon. I’m not necessarily looking for someone to post the answer straight-up, but a little hint in the right direction wouldn’t hurt!
Also, is there a better (i.e. cleaner, simpler, what have you) way of doing this with jQuery? I know it doesn’t particularly matter, but I’m just wondering what it would look like in jQuery, too.
Thank you for reading.
Pass in the whole array in
scoresand your sortFunc extract the first element:http://jsfiddle.net/PS2wS/