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.
Edit:
Regards the data I’m working with, it’s coming back from a web service, and I don’t have the ability to change the text. So I have to work with it as is.
You can use a custom sort function that parses the values out of the text and compares them numerically as described here.
Working demo: http://jsfiddle.net/jfriend00/cf3D7/
You can obviously fine tune the
getVal()function to support whatever parsing logic you want.If your array is large, you can make it perform better by precomputing the sort index and storing it in each object so the custom sort function just directly compares two numbers rather than recalculates it every time. But, arrays less than 100 items that’s probably irrelevant.
Also, it is unclear how you want to sort “More than 1 month ago” and “7-8 weeks”. My current algorithm treats “More than 1 month ago” as 1 month, but you can tweak the parsing logic if you have a particular rule in mind. Once you have the custom sort function, the key to your sort logic is all in the implementation of the
getVal()function which you can tweak to support whatever syntax you want to support.Here’s a version that precomputes the sortKey and thus performs a lot better for large arrays:
P.S. Note the much more efficient array declaration syntax I used in the jsFiddle.