-2

Sort month names in sequence using jQuery

Input

month = [ "Apr","May","Jun","Oct","Nov","Dec","Jul","Aug","Sep"];

Expected Output

month = [ "Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

How can sort month name? sort() function only short alphabatic,alphanumeric or numeric value.

Sadikhasan
  • 18,365
  • 21
  • 80
  • 122

2 Answers2

13

Take an array of all months in the year that is in proper order ( hard coded for reference) and use the indexes of master month array as sort criteria in sort()

var allMonths = ['Jan','Feb','Mar', 'Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

var month = [ "Apr","May","Jun","Oct","Nov","Dec","Jul","Aug","Sep"];

month.sort(function(a,b){
    return allMonths.indexOf(a) > allMonths.indexOf(b);
});

// returns  ["Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

DEMO

Chance Smith
  • 1,211
  • 1
  • 15
  • 32
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Exactly expected output that I want. How can I thanks to you. Really appraciated with you. Many many thanks. – Sadikhasan Dec 22 '14 at 09:48
  • 4
    Am I missing something? This code is wrong. The sort function is supposed to return an integer. You might get lucky sometimes returning a boolean value, but really you should be returning `allMonths.indexOf(a) - allMonths.indexOf(b)` see this question for more info: http://stackoverflow.com/questions/24080785/sorting-in-javascript-shouldnt-returning-a-boolean-be-enough-for-a-comparison – RTF Nov 09 '16 at 17:54
3

In my case, I needed to tweak Chance Smith's answer a bit as suggested by RTF in the comment of the accepted answer to get it working. The modification was changing '>' into '-'. I'm pasting the working code here in case anyone needed.

var allMonths = ['Jan','Feb','Mar', 'Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

var month = [ "Apr","May","Jun","Oct","Nov","Dec","Jul","Aug","Sep"];

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

// returns  ["Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
Sagor Mahtab
  • 147
  • 3
  • 11