Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript sort items list by months

Tags:

javascript

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" } }
        ];
like image 289
A191919 Avatar asked May 20 '16 14:05

A191919


People also ask

How to sort month in JavaScript?

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.

How do I sort by year in JavaScript?

sort((a, b) => a. Year - b. Year); Sorts by year quite simply.


1 Answers

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);
  });
}
like image 165
blex Avatar answered Sep 28 '22 02:09

blex