javascript - 按字符串日期对对象数组进行排序
问题描述
我有一组如此结构化的对象。
let array = [
{date: "22/03/2021 17:57", y: 10, type: "dil"},
{date: "22/03/2021 17:58", y: 1, type: "dil"},
{date: "15/04/2021 14:52", y: 3, type: "dil"},
{date: "24/03/2021 14:52", y: 4, type: "dil"},
{date: "01/04/2021 14:52", y: -2, type: "spp"},
{date: "24/03/2021 14:53", y: -5, type: "spp"},
{date: "18/04/2021 16:28", y: 3, type: "spp}
]
我必须按日期对其进行排序,但我不知道该怎么做,因为日期是一个字符串,如果我使用排序方法
array.sort((a,b) => (a.x > b.x) ? 1 : ((b.x > a.x) ? -1 : 0))
它是根据前两个字符排序的,而不是通过面对年、月、日、小时和分钟来正确排序。
有任何想法吗?我敢肯定这很容易,但我很困惑。
解决方案
您可以创建一个ISO 8601日期字符串并按字符串排序。
const
getISO = string => string.replace(/(..)\/(..)\/(....) (..):(..)/, '$3-$2-$1 $4:$5'),
array = [{ date: "22/03/2021 17:57", y: 10, type: "dil" }, { date: "22/03/2021 17:58", y: 1, type: "dil" }, { date: "15/04/2021 14:52", y: 3, type: "dil" }, { date: "24/03/2021 14:52", y: 4, type: "dil" }, { date: "01/04/2021 14:52", y: -2, type: "spp" }, { date: "24/03/2021 14:53", y: -5, type: "spp" }, { date: "18/04/2021 16:28", y: 3, type: "spp" }];
array.sort((a, b) => getISO(a.date).localeCompare(getISO(b.date)));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- java - 从mybatis读取数据时出现OOM
- matlab - 如何在 MATLAB 中一次性使用同一代码中的两个数据集?
- python - Pygame全屏放大
- file - 如何在 Haskell 中读取 .cfg 文件
- cfml - Cfquery 不工作,附加代码和返回错误
- javascript - 对象数组中的属性名称作为变量?
- group-by - 有没有办法使用使用多列作为新主键的 GROUP BY 语句?(不是一个接一个)
- vue.js - Vue.js 3 替代 `Vue.config.errorHandler`
- python - 使用 math.ceil() 打印下一个正整数,即使数字本身是整数
- docker - 在 docker 容器中找不到包 ipfs、peer 和 shim 包