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.

5
  • It could be that your date property is in string format. Convert it into date first. To avoid duplicating, see this solution. Hope it will be helpfull for you. Commented Jun 15, 2015 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? Commented Jun 15, 2015 at 20:58
  • Maybe this topic 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 :) Commented Jun 16, 2015 at 22:04
  • There is also a problem to combine grouping and ordering with date parameter... Commented Jun 17, 2015 at 0: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. Commented Jun 17, 2015 at 12:25

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

How to do this with angular 2?
The solution is based on pure JS, i.e. does not use any angular component. You need to rewrite same logic in TypeScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.