2

I have a list of items. Each item contains a date property. I want to group all items by month and display them in two nested lists.

Example

  • June 2015

    • Item 1
    • Item 2
    • Item 3
  • May 2015

    • Item 4
    • Item 5
    • Item 6

etc.


Is it possible to achieve this in Angular.js without fiddling with underlying data (i.e. via filters and such)?

I've tried the method described in this topic: How can I group data with an Angular filter?, but it breaks the order of the elements and I have to manually format date to 'MMMM YYYY' before calling groupBy.

Community
  • 1
  • 1
Slava Fomin II
  • 26,865
  • 29
  • 124
  • 202
  • It could be that your date property is in string format. Convert it into date first. To avoid duplicating, see this [solution](http://stackoverflow.com/questions/27734780/how-filter-date-properly-with-angular-js-by-month-and-year/27734935#27734935). Hope it will be helpfull for you. – arman1991 Jun 15 '15 at 12:51
  • Thank you @arman1991 for a response. My date is initially a moment() instance. I couldn't find a way to group items by month and year without first adding another property to hold textual representation of `'MMMM YYYY'`. Is there a way to use `groupby` with moment() or Date instance directly? – Slava Fomin II Jun 15 '15 at 20:58
  • Maybe this [topic](http://stackoverflow.com/questions/20662140/using-angularjs-date-filter-with-utc-date) can help you, the moment.js is also mentioned. I find a way to group with date as described in my previous comment, but for some strange reason, the filtering doesn't work in format that you want... You will be informed if I discover a way without adding the new property :) – arman1991 Jun 16 '15 at 22:04
  • There is also a problem to combine grouping and ordering with date parameter... – arman1991 Jun 17 '15 at 00:25
  • Thank you @arman1991 for taking a time to look into this. I've decided to re-structure the data inside of my controller for now to use simpler rendering functionality. – Slava Fomin II Jun 17 '15 at 12:25

1 Answers1

0

Looks pretty straight forward, just group the items by date and display :

var itemsGroupedByMonth = function (items) {
    var
        groups = [[], [], [], [], [], [], [], [], [], [], [], [],],
        itemGroupedByMonths = [];

    for (var i = 0; i < items.length; i++) {
      groups[items[i].date.getMonth()].push(items[i]);
    }
    for (var i = 0; i < groups.length; i++) {
      if (groups[i].length) {
        itemGroupedByMonths.push({
          month: monthLabels[i],
          items: groups[i]
        });

      }
    }
    return itemGroupedByMonths;
  };

Find a working example here : http://plnkr.co/edit/idvloFKoFvWGdBSGfMsX?p=preview

Nishant
  • 4,659
  • 2
  • 27
  • 43