greatTeacherOnizuka
greatTeacherOnizuka

Reputation: 565

Group array by year

I am hitting a REST API which provides me a set of data contained in an array. The dates are strings.

The following is what the data looks like:

arr = [
    "2015-07-31",
    "2015-08-31",
    "2015-09-30",
    "2015-10-31",
    "2015-11-30",
    "2015-12-31",
    "2016-01-31",
    "2016-02-29",
    "2016-03-31",
    "2016-04-30",
    "2016-05-31",
    "2016-06-30",
    // MORE ITEMS...
]

How would I achieve grouping this array by year (e.g. 2015: July, August, September etc. 2016: January, February, March etc.).

Would a custom pipe helps? And is it better to do the grouping in the controller rather than the service?

Upvotes: 0

Views: 1796

Answers (2)

runit
runit

Reputation: 376

In my opinion it's better to do it directly in the service. So in your service you could have a private method toGroupedYears(arrayOfDates), and then you could the rxjs operator map to do something like this:

//myservice.ts
import 'rxjs/add/operator/map'
...
public getDates(){
  this.http.get(`${this.url}/dates`)
    .map( (dates) => this.toGroupedDates(dates.json()))
}
...

And in the toGroupedDates method you can have something like this:

private toGroupedDates(array){
  // Extract year from arr
  let extractedYear = array.map((date) => {
    return date.split('-')[0];
  });

  // Get just the year list
  let yearsArray = new Set(extractedYear);


  // Group by year
  let filteredByYears = [];
  yearsArray.forEach((year) => {
    filteredByYears.push({ [year] : array.filter((_year) => {
      return _year.split('-')[0] == year; 
    })});
  });
  
  return filteredByYears;
}

Hope it help you :)

Upvotes: 3

linhao
linhao

Reputation: 154

i write an example for you hope it could help you

  yearsGroup: any = {};
  groupByYear(arry: Array<string>) {
    arry.forEach((value) => {
      let date = new Date(value);
      let year = date.getFullYear();
      if (this.yearsGroup[year]) {
        this.yearsGroup[year].push(value);
      } else {
        this.yearsGroup[year] = [];
        this.yearsGroup[year].push(value);
      }
    });

  }

result:

{
  2015:[...],
  2016:[...]
}

Upvotes: 0

Related Questions