Sort string array by analysing date details in those strings

Posted by Jason Evans on Stack Overflow See other posts from Stack Overflow or by Jason Evans
Published on 2012-11-22T16:51:14Z Indexed on 2012/11/22 16:59 UTC
Read the original article Hit count: 194

Filed under:
|

I have a requirement for the project I'm working on right now which is proving a bit tricky for me.

Basically I have to sort an array of items based on the Text property of those items:

Here are my items:

var answers = [],
    answer1 = { Id: 1, Text: '3-4 weeks ago' },
    answer2 = { Id: 2, Text: '1-2 weeks ago' },
    answer3 = { Id: 3, Text: '7-8 weeks ago' },
    answer4 = { Id: 4, Text: '5-6 weeks ago' },
    answer5 = { Id: 5, Text: '1-2 days ago' },
    answer6 = { Id: 6, Text: 'More than 1 month ago' };

answers.push(answer1);
answers.push(answer2);
answers.push(answer3);
answers.push(answer4);
answers.push(answer5);
answers.push(answer6);

I need to analyse the Text property of each item so that, after the sorting, the array looks like this:

answers[0] = { Id: 6, Text: 'More than 1 month ago' }
answers[1] = { Id: 3, Text: '7-8 weeks ago' }
answers[2] = { Id: 4, Text: '5-6 weeks ago' }
answers[3] = { Id: 1, Text: '3-4 weeks ago' }
answers[4] = { Id: 2, Text: '1-2 weeks ago' }
answers[5] = { Id: 5, Text: '1-2 days ago' }

The logic is that, the furthest away the date, the more high priority it is, so it should appear first in the array. So "1-2 days" is less of a priority then "7-8 weeks".

So the logic is that, I need to extract the number values, and then the units (e.g. days, weeks) and somehow sort the array based on those details.

Quite honestly I'm finding it very difficult to come up with a solution, and I'd appreciate any help.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about sorting