swiftcode
swiftcode

Reputation: 3059

Last.fm JSON sorting with JQuery

I'm doing AJAX calls to get data from the last.fm API and decided to use JSON as return data type. So far, so good. The problem is this: I want to get the top tracks using the tag.getTopTags method from the API and it returns me a JSON that isn't sorted by popularity (even though they say it is).

So how do I sort this JSON by count property (that indicates popularity) once I have this in a variable in my code?

Here's a sample of the JSON (pardon the lack of formatting, this is from a link they give on their website). It goes like this: toptags has tag which contains an array of tags, which have name, count, etc...

Here's the method from my code that requests the top tracks (via GET with a PHP file that's on my web server - this is working fine):

var getTopTracks = function() {
    $.getJSON(
      settings.PHP_REQUEST_URL,
      {
        method: "tag.getTopTags",
        api_key: settings.LASTFM_APIKEY,
        format: "json",
        callback: "?"
      },
      function(data) {
        // treat data here
      });
  };

I know how to show the data and stuff, I'd just like to sort the data before I show it. Anyone know how to do this in a simple way?

Upvotes: 0

Views: 193

Answers (1)

Vinay
Vinay

Reputation: 6342

You're going to want to use Array's built-in sort method with a comparator function passed in. In your case:

data.toptags.tag.sort(function (t1, t2) {
    return t1.count - t2.count;
});

The code is pretty self-explanatory, but the way it works is by using the regular sort function provided by the Array prototype and comparing the elements within the array by the comparison function provided. So, when it does comparison checks (like is count1 > than count2?), it will instead get an object in this case and you'll specify that the difference between one tag's count and the other should give precedence to which "ranks" higher in comparison.

Upvotes: 2

Related Questions