Group and Display Data with Underscore and AngularJS

Thursday, August 8, 2013

Let’s use the following data to simulate information you might receive from an HTTP API:

$scope.data =
[
    { department: "engineering", name: "Scott" },
    { department: "engineering", name: "Joy" },
    { department: "sales", name: "Sara" }
];

Using underscore.js, it is easy to group the objects by their department attribute.

$scope.groups = _.groupBy($scope.data, "department");

Now $scope.groups will look like the following:

{"engineering":
   [{"department":"engineering","name":"Scott"},
    {"department":"engineering","name":"Sally"}],
 "sales":
   [{"department":"sales","name":"Fred"}]
}

One way to get the data onto the screen is to use an ngRepeater, but the most popular expression form for the repeater (”variable in expression”) doesn’t exactly give us what we want.

<div data-ng-repeat="department in groups">
    <h4>{{ department }}</h4>        
    <ul>
        <li data-ng-repeat="employee in department">
            {{ employee.name }}
        </li>
    </ul>
</div>

That’s because department will hold each value of the groups collection.

image

What we really want is the lesser known expression supported by Angular: (key, value) in expression.

<div data-ng-repeat="(department, employees) in groups">
    <h2>{{department}}</h2>        
    <ul>
        <li data-ng-repeat="employee in employees">
            {{ employee.name }}
        </li>
    </ul>
</div>

Which gives us:

image

As always, there are 101 ways to achieve this end result, but I rather like the (key, value) expressions myself.


Comments
gravatar Dave Thursday, August 8, 2013
This was super helpful. Thanks! I have noticed that I'm not able to sort or search on the group results. Any thoughts as to why?
gravatar Scott Friday, August 9, 2013
@Dave: Can you post some code on plunkr?
gravatar wayne Saturday, August 10, 2013
I prefer lodash over underscore. Same API but faster.
gravatar Brett Friday, August 16, 2013
Thanks, great tip :)
gravatar Maximilian Eberl Tuesday, August 20, 2013
This is a great Hint!!! Thank You 1000 times! The underscore library is REALLY helpful!
gravatar Francesco Sunday, September 8, 2013
It's possible to have a form with checkboxes and switch the filter to group the record by name and not by department?
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!