你如何比较 JS 中的 "week-year" 值?
How can you compare "week-year" value in JS?
例如,我有以下 String
周-年格式的值:
// 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
为了调度目的,我必须整理出一组具有 "week-year" 值的数组。目前我正在使用 array.sort
来完成这个:
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));
有什么方法可以将 week-year
值修改为允许排序的数值吗?
以上排序应该给我的顺序是:
"1-19" , "5-18" , "4-18"
您可以创建一个格式化的字符串,其中年份在前,然后是填充的周,可以将其作为字符串进行比较。
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; }
例如,我有以下 String
周-年格式的值:
// 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
为了调度目的,我必须整理出一组具有 "week-year" 值的数组。目前我正在使用 array.sort
来完成这个:
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));
有什么方法可以将 week-year
值修改为允许排序的数值吗?
以上排序应该给我的顺序是:
"1-19" , "5-18" , "4-18"
您可以创建一个格式化的字符串,其中年份在前,然后是填充的周,可以将其作为字符串进行比较。
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; }