user3918569
user3918569

Reputation: 83

Underscore.js nested groupings

I'm having trouble getting the output I need from the following json

[
 {"Type":"A","Location":"1"},
 {"Type":"A","Location":"2"},
 {"Type":"A","Location":"3"},
 {"Type":"B","Location":"2"},
 {"Type":"B","Location":"3"},
 {"Type":"C","Location":"1"},
 {"Type":"A","Location":"1"},
 {"Type":"A","Location":"1"},
 {"Type":"A","Location":"3"},
 {"Type":"C","Location":"1"},
 {"Type":"C","Location":"1"},
 {"Type":"C","Location":"1"}
]

my expected output is as follows:

[
 {"Type":"A","Count":"6","Locations":
  [
   {"Location":"1","Count":"3"},
   {"Location":"2","Count":"1"},
   {"Location":"3","Count":"2"}
  ]
 },
 {"Type":"B","Count":"2","Locations":
  [
   {"Location":"2","Count":"1"},
   {"Location":"3","Count":"1"}
  ]
 },
 {"Type":"C","Count":"4","Locations":
  [
   {"Location":"1","Count":"4"}
  ]
 }
]

The code I have so far will group the locations and give me the counts, but I'm stuck with the inner group

var result = _.chain($scope.incidents)
                    .groupBy("Type")
                    .map(function(value,key){
                        return{
                            Type:key,
                            Count:value.length
                        }
                    }).value();

Upvotes: 2

Views: 1019

Answers (2)

tcooc
tcooc

Reputation: 21209

Try this:

var result = _.chain($scope.incidents).groupBy('Type').map(function(value, key) {
  return {
    Count: value.length,
    Type: key,
    Locations: _.chain(value).groupBy('Location').map(function(value, key) {
      return {
        Location: key,
        Count: value.length
      };
    }).value()
  };
}).value();

Upvotes: 2

Patrik Oldsberg
Patrik Oldsberg

Reputation: 1550

I'm assuming you're using Lo-Dash, as underscore didn't seem to have the groupBy(<string>) feature.

In any case, here's a solution:

var result = _(list)
    .groupBy('Type')
    .map(function (locations, type) {
        return {
            Type: type,
            Count: locations.length,
            Locations: _(locations)
                .groupBy('Location')
                .map(function (arr, location) {
                    return {
                        Count: arr.length,
                        Location: location
                    };
                }).value()
        };
    }).value();

Upvotes: 2

Related Questions