1

I am trying to sort a feed that I have called in using Jquery.ajax. I'm trying to sort it by the number of values in an array within the feed.

For example, in this feed, I want to sort it by # of NFL teams in descending, so it would be re-sorted to California, New Jersey, Massachusetts:

[
   {
      "title":"New Jersey",
      "NFLteams":[
         {
            "Name":"Jets",
            "Conference":"AFC",
         },
         {
            "Name":"Giants",
            "Conference":"NFC",
         }
         ]
   },
   {
      "title":"Massachusetts",
      "NFLteams":[
         {
            "Name":"Patriots",
            "Conference":"AFC",
         }
         ]
   },
   {
      "title":"California",
      "NFLteams":[
         {
            "Name":"Raiders",
            "Conference":"AFC",
         },
         {
            "Name":"49ers",
            "Conference":"NFC",
         },
         {
            "Name":"Chargers",
            "Conference":"AFC",
         }
         ]
   }
]

I've tried code like this (from this thread Sorting an array of JavaScript objects), but it doesn't work (even if I make it NFLteams.length):

   var sort_by = function(field, reverse, primer){
   var key = function (x) {return primer ? primer(x[field]) : x[field]};

   return function (a,b) {
      var A = key(a), B = key(b);
      return ( (A < B) ? -1 : ((A > B) ? 1 : 0) ) * [-1,1][+!!reverse];                  
   }
   }
   data.sort(sort_by('NFLteams', false, function(a){return a.toUpperCase()}))    

Any suggestions on how I can sort by the # of values in the array? Thanks to anyone who can help or point me in the right direction.

Community
  • 1
  • 1
ncdev
  • 11
  • 2
  • well, if those values are stored and fetched from DB would be easier to COUNT and compare then sort, just an idea. – Venzentx Sep 02 '13 at 15:49

4 Answers4

4

Your method seems to work if you use the length property of the array:

data.sort(sort_by('NFLteams', false, function(a){return a.length}))

See JsBin: http://jsbin.com/eWafEMe/1/edit

Tibos
  • 27,507
  • 4
  • 50
  • 64
1

Simple function like this will do the trick.

data.sort(function(a,b){
     return b.NFLteams.length - a.NFLteams.length;
});

http://jsfiddle.net/x9d2J/

Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
1

in your sort function reverse the comparison to return in descending order:

.sort(function(team1, team2) {
    return team2.NFLteams.length - team1.NFLteams.length;
});

or multiply the result by -1:

.sort(function(team1, team2) {
    return -1 * (team1.NFLteams.length - team2.NFLteams.length);
});

See the console output from this fiddle

dc5
  • 12,341
  • 2
  • 35
  • 47
0

You can try underscore's sortBy:

_.sortBy(i, function(team){ return team['NFLteams'].length }).reverse();

where i is your input array.

fiddle: http://jsfiddle.net/kMbsW/

cr0
  • 617
  • 5
  • 17