Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

javascript - Sort Complex Array of Arrays by value within

I have an array of arrays in javascript set up within an object that I'm storing with local storage. It's high scores for a Phonegap game in the format {'0':[[score,time],[score,time]} where 0 is the category. I'm able to see the scores using a[1][0]. I want to sort with the high scores first.

var c={'0':[[100,11],[150,12]};
c.sort(function(){
    x=a[0];
    y=b[0];
    return y-x;
}

However, b[0] always gives an undefined error.

I'm new to Javascript and making this is my first major test as a learning experience. Though I've looked at a number of examples on stackoverflow still can't figured this one out.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to declare the parameters to the comparator function.

c.sort(function(){

should be

c.sort(function(a, b){

and you need to call sort on an array as "am not i am" points out so

var c={'0':[[100,11],[150,12]]};
c[0].sort(function(a, b){
    var x=a[0];
    var y=b[0];
    return y-x;
});

leaves c in the following state:

{
  "0": [
    [150, 12],
    [100, 11]
  ]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...