1

I'm try to order objects numerically in an array in ascending order, by using a nested object property, the property being 'score'.

The Array;

[ {name:'dan', score:220},
  {name:'lucy', score:876},
  {name:'mike', score:211} ]

I found the following thread, but have yet managed to get it working.

How to sort a JavaScript array of objects by nested object property?

Console outputs undefined.

function order_top_scores(prop, arr) {
    arr.sort(function (a, b) {
         if (a[prop] < b[prop]) {
        return -1;
         } else if (a[prop] > b[prop]) {
        return 1;
         } else {
        return 0;
         }
    });
};

function get_results(){
    $.get(wp_theme_dir+'/dottodot.php', 
         function(data){ 
        var returnedData = $.parseJSON(data);
        var ordered_scores = order_top_scores(returnedData)     
        console.log(returnedData);

    });
}

My Array differs slightly, could it be the second property thats disrupting the sort? Or maybe the way i'm handling the data from the ajax request.

thanks in advance, Cam

Community
  • 1
  • 1
Cam
  • 960
  • 1
  • 12
  • 29

2 Answers2

2

how are you?

I've just tested this, and there's a couple of things you might want to modify.

First of all, you're using the "sort" solution from the person who asked, not the actual solution, so you first need to rewrite your order_top_scores, like this:

        var order_top_scores = function (prop, arr,reverse) {
            if(!reverse) reverse = 0;
            prop = prop.split('.');
            var len = prop.length;

            arr.sort(function (a, b) {
                var i = 0;
                while( i < len ) { a = a[prop[i]]; b = b[prop[i]]; i++; }
                if (a < b) {
                    return -1;
                } else if (a > b) {
                    return 1;
                } else {
                    return 0;
                }
            });

            if(reverse){arr.reverse()};
            return arr;
        };

Analyzing this function, I've added a third "reverse" parameter, which expects either true or false (because the original solution orders it from lowest to highest, and in this case you want the opposite)

Now that you have this function, there's 2 things you want to keep in mind:

First

In this line:

var ordered_scores = order_top_scores(returnedData);

You are not sending the first mandatory parameter, which actually tells the function which property you want the object sorted by: In this case, "score".

So, you have to call the function like this:

var ordered_scores = order_top_scores('score',returnedData);

And if you want it to be sorted from high to low, like this:

var ordered_scores = order_top_scores('score',returnedData,true);

Second

Also, keep in mind you are outputting the "returnedData" value rather than the ordered_scores value so if this line:

console.log(returnedData);

Is outputting undefined, it means your JSON data is not correct. To be sure the sort worked, you should also output the ordered_scores like this:

console.log(ordered_scores);

Let me know if anything unclear.

Cheers!

fsodano
  • 548
  • 2
  • 8
  • Thanks fsodano, this worked perfectly. The ascending/descending boolean is a nice touch. – Cam Mar 20 '12 at 12:23
0

I am not sure this is the correct code:

var returnedData = $.parseJSON(data);
var ordered_scores = order_top_scores(returnedData)

The following change in order_top_scores and method call may work correctly if returnedData is array as you have mentioned in your question:

function get_results(){
    $.get(wp_theme_dir+'/dottodot.php', 
         function(data){ 
        var returnedData = $.parseJSON(data);
        var ordered_scores = order_top_scores("score", returnedData); 
        console.log(returnedData);

    });
}

function order_top_scores(prop, arr) {
    arr.sort(function (a, b) {
             if (a[prop] < b[prop]) {
            return -1;
             } else if (a[prop] > b[prop]) {
            return 1;
             } else {
            return 0;
             }
        });
}

You can check the output here in console

dhaval
  • 7,611
  • 3
  • 29
  • 38