user3214545
user3214545

Reputation: 2213

Sort array beginning with current month

I have an array of months and years - the month is dispalyed as a number between 1 a 12. I want to sort the array so I can displAy the current month of the current year first.

allMonths = [month: 1 year: 2013 value: 25, 
      month: 1 year: 2014 value: 17,
      month: 2 year: 2013 value: 10,
      month: 2 year: 2014 value: 16,
      month: 3 year: 2013 value: 25, 
      month: 3 year: 2014 value: 17,
      month: 4 year: 2013 value: 10,
      month: 4 year: 2014 value: 16,
      ......etc ]

allMonths.sort(function(a, b){
if (a.year > b.year) 
     return 1;               
if (a.month < b.month) 
     return -1;
}) 

I want the output to show the past 12 months starting at the current month with it's value (I don't need to display the year)...

4: 16 (Apr 2014)
3 : 17(March 2014)
2: 16 (Feb  2014)
1: 16 (Jan 2014)
12 : 17(Dec 2013)
11: 16 (Nov 2013)
...etc

I haven't had much experience sorting arrays so i'm a bit lost

Upvotes: 1

Views: 1495

Answers (2)

Bergi
Bergi

Reputation: 664599

Have a look at Sorting in JavaScript: Should every compare function have a "return 0" statement?. Also notice that when the year/month is not greater than the other, it still might be smaller, which needs to take precedence over the further ordering. Try

allMonths.sort(function(a, b) {
    if (a.year > b.year)
         return 1;
    if (a.year < b.year)
         return -1;
    if (a.month > b.month)
         return 1;
    if (a.month < b.month)
         return -1;
    return 0;
})

A shorter way to write a numeric comparison function would be

allMonths.sort(function(a, b) {
    return a.year-b.year || a.month-b.month;
})

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239483

If the years are the same, return the difference between the months, otherwise return the difference between the years itself.

allMonths.sort(function(a, b) {
    if (a.year === b.year) {
        return a.month - b.month;
    }
    return a.year - b.year;
});

If you want to sort the array in the descending order (most recent things first), just swap the order in which the years and months are compared, like this

allMonths.sort(function(a, b) {
    if (a.year === b.year) {
        return b.month - a.month;
    }
    return b.year - a.year;
});

It can be written succinctly with ternary expression, like this

allMonths.sort(function(a, b) {
    return a.year === b.year ? b.month - a.month : b.year - a.year;
});

Note: JavaScript's sort is not guaranteed to be stable.

Upvotes: 2

Related Questions