javascript - 基于字符串值的数组排序不起作用
问题描述
我正在尝试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" }
如上所示,数组未正确排序。一个字段放错了位置。难道我做错了什么?
以下所有答案都有效,我选择了我已实施的答案。感谢大家。
解决方案
您可以先解析这些日期,然后再-
对它们进行排序。
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)
推荐阅读
- mongodb - 如何在 MongoDB 输入步骤中的 PDI 中使用日期?
- flask - 使用sqlalchemy的flask中的两个数据库,一个用于读取数据,一个用于写入数据,是否可以
- python - 文字不会排列
- prestashop - 无法让 Prestashop Bitnami Stack 1.7 在 Windows 上运行
- javascript - React js css loader 给出了编译失败的问题
- arrays - 将 eloqvent 对象转换为数组
- javascript - 检查用户名是否有来自名称的 4 个连续字母 - javascript
- javascript - 如何从antd Image中删除编辑器图标
- c# - 使动态创建的面板在 winform 响应式(与我的 flowlayoutPanel 大小相同) - C#
- android - 将数据插入具有外键约束的表时面临问题