Reputation: 127
For example, I have the following String
values in week-year format:
// week-year
"8-18" < "9-18" // returns true
"8-18" < "10-18" // returns false but should return true
"8-18" < "4-18" // returns false but should be true
I have to sort out an array of arrays with "week-year" values for scheduling purposes. Currently I'm using array.sort
to accomplish this:
var results = [
[
{ weekyear:"4-18" }
],
[
{ weekyear:"5-18" }
],
[
{ weekyear: "1-19" }
] ... ]
results.sort((function (index) { // Sort based on Week-Year in descending order
return function (a, b) {
return (a[index].weekyear === b[index].weekyear ? 0 : (a[index].weekyear< b[index].weekyear ? -1 : 1));
};
})(0));
Is there any way I can perhaps modify the week-year
value into a numerical value that allows sorting?
The above sort should give me in order:
"1-19" , "5-18" , "4-18"
Upvotes: 1
Views: 280
Reputation: 386560
You could create a formatted string where the year comes first, followed by a padded week, which could be compared as string.
function getYearWeek(weekYear) {
return weekYear
.split('-')
.map(s => s.padStart(2, '0'))
.reverse()
.join('-W');
}
var results = [{ weekyear: "4-20" }, { weekyear: "5-18" }, { weekyear: "4-18" }, { weekyear: "1-19" }];
console.log(getYearWeek("8-18") < getYearWeek("9-18")); // true
console.log(getYearWeek("8-18") < getYearWeek("10-18")); // true
console.log(getYearWeek("8-18") < getYearWeek("4-18")); // false
results.sort((a, b) =>
getYearWeek(a.weekyear).localeCompare(getYearWeek(b.weekyear)));
console.log(results);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1