3

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?

1 Answer 1

6

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');
Sign up to request clarification or add additional context in comments.

3 Comments

This is a nice and quick way to do it! Thanks Sami
The docs don't guarantee groupBy is stable, right? This is a lucky implementation detail?
lodash in contrast does guarantee a stable ordering when using groupBy: lodash.com/docs/4.17.10#groupBy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.