JavaScript sort items list by months

You can do it by having a list of all the months in the right order, and sorting your array based on them:

var dataCollection = [
  { values: { Month: { displayValue: "August" }, Sum: "10" } },
  { values: { Month: { displayValue: "February" }, Sum: "25" } },
  { values: { Month: { displayValue: "July" }, Sum: "35" } }
];

sortByMonth(dataCollection);

console.log(dataCollection);

function sortByMonth(arr) {
  var months = ["January", "February", "March", "April", "May", "June",
  	        "July", "August", "September", "October", "November", "December"];
  arr.sort(function(a, b){
      return months.indexOf(a.values.Month.displayValue)
           - months.indexOf(b.values.Month.displayValue);
  });
}

Tags:

Javascript