Reputation: 185
I'm trying to apply group and sort on objects.
var emplData = [{
"company": "companyA",
"title": "positionA",
"office": "Boston",
"first-name": "Mike",
"last-name": "Bloom",
"profile-url": "url"
}, {
"company": "companyA",
"title": "positionD",
"office": "Amsterdam",
"first-name": "Adam",
"last-name": "Smart",
"profile-url": "url"
}, {
"company": "companyB",
"title": "positionB",
"office": "Toronto",
"first-name": "Tina",
"last-name": "Carmichael",
"profile-url": "url"
}, {
"company": "companyB",
"title": "positionA",
"office": "Chicago",
"first-name": "Seth",
"last-name": "Big",
"profile-url": "url"
}, {
"company": "companyC",
"title": "positionC",
"office": "St. Louis",
"first-name": "Carla",
"last-name": "Elsas",
"profile-url": "url"
}]
I like to group the data by company
and then sort by office (ascending order). I'm using underscore.js to group and it returns similar to object below.
var grpData = _.groupBy(emplData, 'company');
{
CompanyA:[{object1}, {object2} etc.],
CompanyB: [{object1}, {object2} etc.],
CompanyC: [{object1}, {object2} etc.]
}
Now each object inside the grouped array has properties including office, I can't get the results I need to sort the data by it so we have an ascending order.
I have tried below method but doesn't seem to work.
var srtData = _.sortBy(grpData , function (i) {
$(i).each(function (i2, val) {
return val.office;
});
});
Anyone know a solution for this?
Upvotes: 3
Views: 5929
Reputation: 4006
Why not sort and then group? Then the result will be a collection grouped by company name each holding sorted array of objects (asc. by office name)
var grpData = _.groupBy(_.sortBy(emplData, "office"), 'company');
Upvotes: 6