4

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.

4
  • Where/how are a and b defined? Commented Feb 16, 2012 at 17:40
  • The examples you've given are syntactically incorrect: this is missing a square bracket: {'0':[[score,time],[score,time]} Commented Feb 16, 2012 at 17:40
  • @Jeff a and b are the default .sort parameters. So a[0] should be the first item in the array? Commented Feb 16, 2012 at 18:01
  • @Matt thanks! I was re-typing for the post and missed that Commented Feb 16, 2012 at 18:03

3 Answers 3

7

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]
  ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Mike Thanks for the quick and awesome response! I had been looking at examples here and on Google for days... I didn't realize I had to have the parameters (a,b) in the function. Just added the code and my scores are in the right order finally!
0
function largestOfFour(arr) {

    for(var x = 0; x < arr.length; x++){
        arr[x] = arr[x].sort(function(a,b){
            return b - a;
        });
    }

    return arr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Comments

0

var myArray = [ [11, 5, 6, 3, 10], [22,55,33,66,11,00], [32, 35, 37, 39], [1000, 1001, 1002, 1003, 999]];

_.eachRight(myArray, function(value) {
  var descending = _.sortBy(value).reverse();
  console.log(descending);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>

Comments

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.