JavaScript sort items list by months
I am playing with js scripts. How to sort items of list by months. What is the best way to do it?
var dataCollection = [
{ values: { Month: { displayValue: "August" }, Sum: "10" } },
{ values: { Month: { displayValue: "February" }, Sum: "25" } },
{ values: { Month: { displayValue: "July" }, Sum: "35" } }
];
I expect to get
dataCollection = [
{ values: { Month: { displayValue: "February" }, Sum: "25" } },
{ values: { Month: { displayValue: "July" }, Sum: "35" } },
{ values: { Month: { displayValue: "August" }, Sum: "10" } }
];
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);
});
}