Best way to group and sort an array of objects

javascript, underscore.js

Solution

You can do the sort across the entire array first and then group by:

JSFIDDLE

var demoData= [{"EntryGroupDate":"November 2013", 
                "DisplayName": "Hans Meier (November)", 
                "EntryGroupDateSort": 11},
               {"EntryGroupDate":"August 2013", 
                "DisplayName": "Franz Mueller (August)", 
                "EntryGroupDateSort": 8},
               {"EntryGroupDate":"November 2013", 
                "DisplayName": "Franz Huber (November)", 
                "EntryGroupDateSort": 11},
               {"EntryGroupDate":"Juli 2013", 
                "DisplayName": "Franz Schmidt (Juli)", 
                "EntryGroupDateSort": 7}
              ];


_.sortBy( demoData, function(x){ return x.EntryGroupDateSort; } );
groups = _.groupBy( demoData, 'EntryGroupDate' );
console.log( groups );

If you want to sort after grouping then you can use (sorting on `DisplayName` this time):

JSFIDDLE

groups = _.groupBy( demoData, 'EntryGroupDate' );
for ( var key in groups )
    groups[key].sort( function(a,b){ var x = a.DisplayName, y = b.DisplayName; return x === y ? 0 : x < y ? -1 : 1; } );
console.log( groups );

Problem

I have the following demo data. ``` var demoData= [{"EntryGroupDate":"November 2013", "DisplayName": "Hans Meier (November)", "EntryGroupDateSort": 11}, {"EntryGroupDate":"August 2013", "DisplayName": "Franz Mueller (August)", "EntryGroupDateSort": 8}, {"EntryGroupDate":"November 2013", "DisplayName": "Franz Huber (November)", "EntryGroupDateSort": 11}, {"EntryGroupDate":"Juli 2013", "DisplayName": "Franz Schmidt (Juli)", "EntryGroupDateSort": 7} ]; ``` What would be the best way to group them first by `EntryGroupDateSort` and sort them afterwards by the same criteria. For the output I need all the information of the original array. I have just fiddled around with UnderscoreJS but did not get the desired result by using the following code. ``` var myPersons = demoData; var groups = _.groupBy(myPersons, "EntryGroupDate"); console.log(groups); groups = _(groups).sortBy(function (item) { return item.EntryGroupDateSort; }); console.log(groups); ``` The first console output shows the data in the format I would like to have after sorting the data. Hopefully someone can point me in the right direction.

Original source