gpt4 book ai didi

javascript - 基于字符串值的数组排序不起作用

转载 作者:行者123 更新时间:2023-11-30 07:07:08 24 4
gpt4 key购买 nike

我正在尝试使用 String 字段对 Array 进行排序,但排序错误。

我的代码是这样的。

 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" }

如上所示,数组未正确排序。一个字段放错了地方。我做错了什么吗?

以下所有答案均有效,我选择了已实现的答案。谢谢大家。

最佳答案

您可以先解析这些日期,然后使用 - 对它们进行排序。

let arr = [{"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 parse = str => {
let date = new Date;
let [month, year] = str.split('/')
date.setYear(year);
date.setMonth(+month - 1)
return date;
}

const sortBy = prop => (a, b) => {
return parse(b[prop]) - parse(a[prop])
}

arr.sort(sortBy('to'))
console.log(arr)

关于javascript - 基于字符串值的数组排序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53957040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com