3

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.

4
  • Let me clarify: you'd like to sort the players along with the names right? Commented Apr 9, 2012 at 3:49
  • I suppose sorting the players would work as well, yes. I just want to be able to order the names properly with who is in first, second, third, etc., no matter how it's accomplished. Commented Apr 9, 2012 at 3:51
  • I've added an answer, please see if that fits your requirements :) Commented Apr 9, 2012 at 3:51
  • Instead of using jQuery to do this you might want to take a look at underscore.js it has a bunch of neat functions to deal with javascript's built in data structures as well as some functional helpers. heres the sortBy documentation Commented Apr 9, 2012 at 3:57

1 Answer 1

4

Pass in the whole array in scores and your sortFunc extract the first element:

http://jsfiddle.net/PS2wS/

var player1 = ["bob", 20];
var player2 = ["jon", 40];
var player3 = ["tim", 10];
var scores = [player1, player2, player3];

scores.sort(sortfunc);

function sortfunc(a,b){
  return a[1] - b[1];
}
Sign up to request clarification or add additional context in comments.

3 Comments

That is absolutely what I wanted. I see what you did by passing the entire array and then sorting just by the score. Unfortunately, I utterly fail to understand why passing the entire array works the way it does, so I guess my grasp on multidimensional arrays is tenuous at best. Regardless, thank you for solving it.
I'll be awarding you the answer in 3 minutes when it allows me. =)
@daveycroqet the callback in the first argument of sort() takes two parameter, which is the direct first level members of the array sort() is called upon. So in my answer, a and b would be player1, player2 and player3. We are telling it how to return the order by doing a substraction of the first element of playerX, which is the score.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.