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" } }
];
What is the best way to do it? dataCollection = [ { values: { Month: { displayValue: "February" }, Sum: "25" } }, { values: { Month: { displayValue: "July" }, Sum: "35" } }, { values: { Month: { displayValue: "August" }, Sum: "10" } } ]; javascript.
sort((a, b) => a. Year - b. Year); Sorts by year quite simply.
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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With