我正在尝试使用Array
字段对String
进行排序,但排序错误。
我的代码如下。
let tempWEArray = [
{
"from" : "09/2005",
"to" : "11/2006"
},
{
"from" : "09/2006",
"to" : "11/2007"
},
{
"from" : "12/2007",
"to" : "01/2009"
},
{
"from" : "01/2009",
"to" : "12/2012"
},
{
"from" : "01/2013",
"to" : "03/2018"
}]
function sortBy(prop){
return function(a,b){
if( a[prop] < b[prop])
{
return -1;
}
else if( a[prop] > b[prop] )
{
return 1;
}
return 0;
}
}
console.log(tempWEArray.sort(sortBy("to")))
获得的输出如下。
0: Object { from: "12/2007", to: "01/2009" }
1: Object { from: "01/2013", to: "03/2018" }
2: Object { from: "09/2005", to: "11/2006" }
3: Object { from: "09/2006", to: "11/2007" }
4: Object { from: "01/2009", to: "12/2012" }
如上所示,数组未正确排序。一个字段放错了位置。我做错什么了吗?
以下所有答案均有效,我已经选择了已实现的答案。谢谢大家。
答案 0 :(得分:3)
您可以先解析这些日期,然后使用<AndroidEnableDesugar>true</AndroidEnableDesugar>
对其进行排序。
-
答案 1 :(得分:2)
将其转换为您喜欢的日期,即可按预期工作。
分离日期字符串的每个部分并反转
const dateArray = b[prop].split("/").reverse()
使用传播运算符使用Date.UTC创建时间戳,然后使用new Date
创建日期。
new Date(Date.UTC(...dateArray))
然后在两个日期之间使用-
来查找排序函数中哪个更大。
一些示例:
const res = new Date(Date.UTC(..."11/2006".split("/").reverse()))
console.log(res);
完整解决方案:
let tempWEArray = [{"from":"09/2005","to":"11/2006"},{"from":"09/2006","to":"11/2007"},{"from":"12/2007","to": "01/2009"},{"from":"01/2009","to": "12/2012"},{"from":"01/2013","to": "03/2018"}]
function sortBy(prop) {
return function(a, b) {
const dateArr1 = a[prop].split("/").reverse();
const dateArr2 = b[prop].split("/").reverse();
//make sure months are between 0 and 11
//can be skipped if this is already ensured.
dateArr1[1]--;
dateArr2[1]--;
return new Date(Date.UTC(...dateArr2)) - new Date(Date.UTC(...dateArr1));
}
}
console.log(tempWEArray.sort(sortBy("to")))
答案 2 :(得分:2)
您可以使用moment.js进行日期露营。例如:
let tempWEArray = [
{
"from" : "09/2005",
"to" : "11/2006"
},
{
"from" : "09/2006",
"to" : "11/2007"
},
{
"from" : "12/2007",
"to" : "01/2009"
},
{
"from" : "01/2009",
"to" : "12/2012"
},
{
"from" : "01/2013",
"to" : "03/2018"
}];
const sortedArray = tempWEArray.sort(
(first, second) => moment(first.to, 'MM/YYYY')
.isSameOrAfter(moment(second.to, 'MM/YYYY')));
console.log(sortedArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
答案 3 :(得分:2)
function sortBy(prop) {
return function(a, b) {
const dateArray = b[prop].split("/").reverse()
console.log()
}
}
答案 4 :(得分:1)
您可以用可比较的字符串替换日期模式,如果该字符串没有日期模式,则可以省略。
function sortBy(prop){
return function(a,b){
var valueA = a[prop].replace(/^(\d{2})\/(\d{4})$/, '$2-$1'),
valueB = b[prop].replace(/^(\d{2})\/(\d{4})$/, '$2-$1');
return valueA.localeCompare(valueB);
}
}
var tempWEArray = [{ from: "09/2005", to: "11/2006" }, { from: "09/2006", to: "11/2007" }, { from: "12/2007", to: "01/2009" }, { from: "01/2009", to: "12/2012" }, { from: "01/2013", to: "03/2018" }]
console.log(tempWEArray.sort(sortBy("to")))
.as-console-wrapper { max-height: 100% !important; top: 0; }