0

I want to do an ng-repeat over an array, skipping certain properties when they are duplicates of a previous iteration.

Model ("events" array)

[
   {
   "id": "event1",
   "date": "June 1st"
   },
   {
   "id": "event2",
   "date": "June 2nd"
   },
   {
   "id": "event3",
   "date": "June 2nd"
   },
   {
   "id": "event4",
   "date": "June 3rd"
   }
]

As you can see the date is duplicated for event2 and event3...

HTML

<div ng-repeat="event in events">  
  <h2>{{event.date}}</h2>
  <p>{{event.id}}</p>
  <hr>
</div>

So the desired result is:


June 1st
event1


June 2nd
event2
event3


June 3rd
event4


My guess is it is something like:

<div ng-repeat="event in events">  
  <h2 ng-if="<!--expression here-->">{{event.date}}</h2>
  <p>{{event.id}}</p>
  <hr>
</div>

Would it be a function in my controller attached to a variable called in the ng-if attribute?

And primarily, how would I form that expression to do what I want in this case?

Note: It is ONLY the rendering of the date variable I want to avoid, not the entire ng-repeat element.

Any help, or alternative suggestions would be appreciated.

Paulos3000
  • 3,355
  • 10
  • 35
  • 68
  • 1
    You have to use something like `group by` on the date variable. Please see this [post](http://stackoverflow.com/questions/23493063/angular-ng-repeat-conditional-wrap-items-in-element-group-items-in-ng-repeat) – Saad May 16 '16 at 08:30
  • Possible duplicate of [How to make ng-repeat filter out duplicate results](http://stackoverflow.com/questions/15914658/how-to-make-ng-repeat-filter-out-duplicate-results) – James P May 16 '16 at 08:31
  • Saad - that looks like a decent solution. Thanks! – Paulos3000 May 16 '16 at 08:42

1 Answers1

0

You can create a custom filter to filter out the unique items:

app.filter('uniq', function() {
    return function(items, param) {
        var filteredItems = [];
        items.forEach(function(item) {
            var found = filteredItems.some(function(elem) {
                return elem.param === item.param;
            });
            if(!found) {
                filteredItems.push(item);   
            }
        });
        return filteredItems; 
    }
});

Use it like this:

event in events | uniq: 'date'
Tarun Dugar
  • 8,921
  • 8
  • 42
  • 79