Reputation: 49404
I am reading some json data and listing it on my page.
One of the values in the json data is score ... "val.score"
This tells me the score of the username.
I've also added a count variable.
What I need to do it to order the list starting with the hightest user score.
Here is my current code:
var count = 1;
$.each(jsonData.listing, function(key, val) {
$("#output").append('<li>Rank'+count+' username'+val.username+'score'+val.score+'</li>');
count++;
});
Upvotes: 2
Views: 80
Reputation: 748
Simply sort your listing before you go through it ($.each):
jsonData.listing.sort(function(x,y){
if(x.score === y.score) return 0;
return x.score < y.score ? 1 : -1;
});
Upvotes: 2
Reputation: 2667
Use sort
:
var count = 1;
var listing = jsonData.listing.sort(function (a, b) { return b.score - a.score; });
$.each(listing, function(key, val) {
$("#output").append('<li>Rank'+count+' username'+val.username+'score'+val.score+'</li>');
count++;
});
Upvotes: 6