Search code examples
javascriptarraysangularsortinglodash

Sort array by year and month


I have the array as below,

let  yearAndMonth  =  [
    { "year": 2013, "month": "FEBRUARY" },
    { "year": 2015, "month": "MARCH" },
    { "year": 2013, "month": "JANUARY" },
    { "year": 2015, "month": "FEBRUARY" }
]

I want to sort the array by year first and after that sort month from the year,

I want the output like this,

yearAndMonth  =  [
    { "year": 2013, "month": "JANUARY " },
    { "year": 2013, "month": "FEBRUARY" },
    { "year": 2015, "month": "FEBRUARY" },
    { "year": 2015, "month": "MARCH" }
]

How to achieve this?


Solution

  • You can also use lodash library for sorting data by multiple column.

    I have created a demo on Stackblitz. I hope this will help/guide to you/others.

    lodash - Documentation

    Component.html

    <table width="100%">
      <tr>
        <td>Year</td>
        <td>Month</td>
      </tr>
      <tr *ngFor="let datas of sortedData">
        <td>{{datas.year}}</td>
        <td>{{datas.month}}</td>
      </tr>
    </table>
    

    Component.ts

     sortedData: any[];
      data = [
        { "year": 2013, "month": "FEBRUARY" },
        { "year": 2015, "month": "MARCH" },
        { "year": 2013, "month": "JANUARY" },
        { "year": 2013, "month": "MARCH" },
        { "year": 2013, "month": "APRIL" },
        { "year": 2015, "month": "FEBRUARY" }
      ];
    
    monthArray: any = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
            "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
    
      ngOnInit() {
        this.sortedData = _.orderBy(data, [(datas) => datas.year, (user) => (this.monthArray.indexOf(user.month))], ["asc", "asc"]);
        console.log(this.sortedData);
      }