OdeToCode IC Logo

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:


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>        
        <li data-ng-repeat="employee in department">
            {{ employee.name }}

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


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

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

Which gives us:


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

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 closed.