0

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.

2
  • 1
    Any reason you have a 2d array there and not an array of objects? Commented Oct 20, 2013 at 9:12
  • This array is coming from some other function call and i dont have any control on that. If I have to convert that into object and reconstruct the array, is there any example which i can use? Commented Oct 20, 2013 at 9:16

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.