ua_boaz ua_boaz - 3 months ago 16
Javascript Question

javascript sort array of objects by quarterly-yearly data

i have an array of data containing objects like below

[
{
"name":"Q1'2016",
"y":0
},
{
"name":"Q2'2016",
"y":0
},
{
"name":"Q3'2016",
"y":0
},
{
"name":"Q4'2015",
"y":0
}
]


i want to sort them based on quarterly, so Q4'2015 should come first, than Q1'2016 and so on.

How can this be achived?

Answer

You can use the sort method and give it a callback to sort your object based on a predicate; in your case, you want to inspect the objects' name property containing your quarter-year information. Since you'll likely have data with different quarters and years, you'll want to map the quarters to month values so you can convert them to year/month dates and compare them that way.

    var data = [  
       {  
          "name":"Q1'2016",
          "y":0
       },
       {  
          "name":"Q2'2016",
          "y":0
       },
       {  
          "name":"Q3'2016",
          "y":0
       },
       {  
          "name":"Q4'2015",
          "y":0
       }
    ];

    var quarterToMonthMap = {
      "Q1": 0,
      "Q2": 3,
      "Q3": 6,
      "Q4": 9
     }
     
    function sortByQuarterYear(lhs, rhs) {
       var lhsQuarterYear = lhs.name.split("'");
       var rhsQuarterYear = rhs.name.split("'");
       var lhsDate = new Date(lhsQuarterYear[1], quarterToMonthMap[lhsQuarterYear[0]]);
       var rhsDate = new Date(rhsQuarterYear[1], quarterToMonthMap[rhsQuarterYear[0]]);
       if (lhsDate.getTime() < rhsDate.getTime()) {
         return -1;
       }
       else if (lhsDate.getTime() > rhsDate.getTime()) {
         return 1;
       }
       else {
         return 0;
       }
     }
       
    document.write(JSON.stringify(data.sort(sortByQuarterYear)));