jquery - JavaScript sort an array of arrays by the day of the week -


i have following variable (console.log(response)):

"['2013-04-15', 26]", "['2013-04-16', 10]", "['2013-04-17', 51]", "['2013-04-18', 46]", "['2013-04-19', 32]", "['2013-04-20', 50]", "['2013-04-21', 26]", "['2013-04-22', 31]", "['2013-04-23', 48]", "['2013-04-24', 821]", "['2013-04-25', 917]", "['2013-04-26', 949]", "['2013-04-27', 405]", "['2013-04-28', 593]", "['2013-04-29', 925]", "['2013-04-30', 877]", "['2013-05-01', 277]", "['2013-05-02', 112]", "['2013-05-03', 115]", "['2013-05-04', 62]", "['2013-05-05', 74]", "['2013-05-06', 76]", "['2013-05-07', 51]", "['2013-05-08', 93]", "['2013-05-09', 231]", "['2013-05-10', 350]", "['2013-05-11', 258]", "['2013-05-12', 0]", "['2013-05-13', 61]" 

which transform in array of arrays in following manner:

var json = response.replace(/"/g,''); json = "[" + json + "]"; json = json.replace(/'/g,'"'); var mydata = json.parse(json); 

and receive (console.log(mydata)):

mydata = [array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2], array[2]] 

which need keep in format further usage. want know if possible sort response day of week? , if possible store in variable example monday days, tuesday days in 1 , on? have use jquery this, function suits needs?

you can use method sort() passing custom sorter function parameter (see below).
in order day-of-week of date corresponding each array's 1st element (e.g. "2013-04-15"), can use date's getday() function.

var sorter = function(a, b) {     /* '.replace("-", "/")' part compatibility safari        see http://stackoverflow.com/questions/4310953/invalid-date-in-safari */     var d1 = new date(a[0].replace("-", "/")).getday();     var d2 = new date(b[0].replace("-", "/")).getday();     return d1 - d2; }; mydata.sort(sorter); 

note:
getday() returns integer between 0 , 6 (inclusive), correspond days-of-week sunday through saturday (sunday 0, monday 1...).

if want classify them day-of-week instead of sorting, can use this:

function classifybydayofweek(customarr) {     var bydayofweek = [[], [], [], [], [], [], []];     (var = 0; < customarr.length; i++) {         var day = new date(customarr[i][0]).getday();         bydayofweek[day].push(customarr[i]);     };     return bydayofweek; } mydata = classifybydayofweek(mydata); 

see short demo.


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -