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