Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array by year and month [closed]

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?

like image 917
Aniket Avhad Avatar asked Aug 18 '18 09:08

Aniket Avhad


2 Answers

You could take an object for the month names and their numerical value.

The chain the order by taking the delta of year and month.

var array =  [{ year: 2013, month: "FEBRUARY" }, { year: 2015, month: "MARCH" }, { year: 2013, month: "JANUARY" }, { year: 2015, month: "FEBRUARY" }];

array.sort(function (a, b) {
    var MONTH = { JANUARY: 0, FEBRUARY: 1, MARCH: 2, APRIL: 3, MAY: 4, JUNE: 5, JULY: 6, AUGUST: 7, SEPTEMBER: 8, OCTOBER: 9, NOVEMBER: 10, DECEMBER: 11 };
    return a.year - b.year || MONTH[a.month] - MONTH[b.month];
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 57
Nina Scholz Avatar answered Sep 17 '22 12:09

Nina Scholz


You can create an array for months names and sort like this:

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

let months = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
              "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];

data.sort(
 (a, b) => (a.year - b.year) || (months.indexOf(a.month) - months.indexOf(b.month))
);


console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 44
Mohammad Usman Avatar answered Sep 20 '22 12:09

Mohammad Usman