Reputation: 95
I am trying to sort the multi dimensional array on a date column. The first date in each row is start date and second one is end date. I want to sort the rows in ascending order based on start date.
The datastructure is:
data = [["p1aprd", "Monthly", "PRD", "Date {Wed Nov 06 2013 01:27:00 GMT-0800 (Pacific Daylight Time)}", "Date {Thu Nov 07 2013 01:28:00 GMT-0800 (Pacific Daylight Time)}", "2"],
["p1aprd", "Monthly", "PRD", "Date {Tue Nov 05 2013 01:29:00 GMT-0800 (Pacific Daylight Time)}", "Date {Wed Nov 06 2013 01:29:00 GMT-0800 (Pacific Daylight Time)}", "2"],
["p1aprd", "Monthly", "PRD", "Date {Mon Nov 04 2013 01:31:00 GMT-0800 (Pacific Daylight Time)}", "Date {Thu Nov 14 2013 01:31:00 GMT-0800 (Pacific Daylight Time)}", "2"],
["p1aprd", "Monthly", "PRD", "Date {Mon Nov 04 2013 01:00:00 GMT-0800 (Pacific Daylight Time)}", "Date {Thu Nov 14 2013 01:38:00 GMT-0800 (Pacific Daylight Time)}", "2"]];
I am trying the function:
data.sort((function(index){
return function(a, b){
return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
};})(4));
alert(data);
I tried all possible solutions suggested here but no luck. I might be overlooking some simple error here. Any help is really appreciated.
Upvotes: 0
Views: 1098
Reputation: 8225
2 problems with your code: 1. you are comparing date string and not date. 2. you are passing 4 whereas index of start date is 3.
Try this:
function getDateFromString(str){ return new Date(str.match(/\{(.*) \(/)[1]); }
data.sort((function(index){
return function(a, b){
a = getDateFromString(a[index]);
b = getDateFromString(b[index]);
return a - b;
};
})(3));
alert(data);
Upvotes: 1