ua_boaz ua_boaz - 3 months ago 9
JSON Question

Sort array of objects by quarterly-yearly data in JavaScript

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, then Q1'2016 and so on.

How can this be acheived?

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]]);
  return lhsDate.getTime() - rhsDate.getTime();
}

document.write(JSON.stringify(data.sort(sortByQuarterYear)));

Comments