Search code examples
javascriptangularsortingangular-materialangular7

How to sort the month list from January to December in angular?


Browser is sorting the month list by default in alphabetical order.How can I sort it in months order? Here is the object data in the .ts file :

 objdata:{ '2017': 
   { total: 150000,
     data: 
      { January: 1200,
        February: 1200,
        March: 1300,
        April: 1300,
        May: 1200,
        June: 2000,
        July: 5000,
        August: 4000,
        September: 4500,
        October: 1200,
        November: 9000,
        December: 9000 } },
  '2018': 
   { total: 20000,
     data: 
      { January: 1200,
        February: 1200,
        March: 1300,
        April: 1300,
        May: 1200,
        June: 2000,
        July: 5000,
        August: 4000,
        September: 4500,
        October: 1200,
        November: 9000,
        December: 9000 } }
}

I am using *ngFor for showing the data :

 <tr *ngFor="let item of objdata | keyvalue">
      <td scope="row">
        <mat-accordion>
          <mat-expansion-panel>
            <mat-expansion-panel-header>
              <mat-panel-title>
                Year {{item.key}}
              </mat-panel-title>
              <mat-panel-description> 
                  {{item.value['total']}}
              </mat-panel-description>
            </mat-expansion-panel-header>
            <div class="row" *ngFor="let subitem of item.value['data'] | keyvalue">
              <label class="col-sm-3 col-form-label">{{subitem.key | titlecase}}</label>
              <label class="col-sm-9 col-form-label">{{subitem.value}}</label>
            </div>
          </mat-expansion-panel>
        </mat-accordion>
      </td>
    </tr>

How can I sort this like january,february,march...... and so on?


Solution

  • Working Demo

    You can create a pipe like this:

    import { Pipe, PipeTransform } from "@angular/core";
    
    @Pipe({
      name: "sortMonth"
    })
    export class SortMonthPipe implements PipeTransform {
      transform(value: any, args?: any): any {
        console.log(value);
        var months = [
          "January",
          "February",
          "March",
          "April",
          "May",
          "June",
          "July",
          "August",
          "September",
          "October",
          "November",
          "December"
        ];
        value.sort(function(a, b) {
          return (
            months.indexOf(a.key) -
            months.indexOf(b.key)
          );
        });
        return value;
      }
    }
    

    .html

    <div class="row" *ngFor="let subitem of item.value['data'] | keyvalue | sortMonth">
         <label class="col-sm-3 col-form-label">{{subitem.key | titlecase}}</label>
         <label class="col-sm-9 col-form-label">{{subitem.value}}</label>
    </div>