Sort arrays with arrays in them
How would I go about doing this? I've tried it, but then it cancels out the array in side of the array I sort and it just becomes a string. Example:
p=new Array
p[0]=[0,"Pl开发者_如何学Cayer 1"]
p[1]=[10,"Player 2"]
p[2]=[2,"Player 3"]
How would I make it sort p by p[x][0] but not make it a string?
You can pass the "sort" method a function to use:
var ps = p.sort(function(p1, p2) { return p1[0] - p2[0]; });
That sorts the array of arrays by the first element of each "row" in the main array. The sort function is passed two elements of the array being sorted, and should return a numeric value that represents the ordering of the two values: negative means p1 is less than p2; zero means they're equal; and a positive number means p2 is less than p1. (Here "less than" means, "should go before in the sorted result".)
精彩评论