Sadikhasan Sadikhasan - 29 days ago 16
jQuery Question

Sort month names

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.

Answer

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

Comments