简体   繁体   中英

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,"Player 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".)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM