Satch3000
Satch3000

Reputation: 49404

jQuery Json order list by hightest number in json value

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

Answers (2)

Philipp Dahse
Philipp Dahse

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

Inpego
Inpego

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

Related Questions