我有一个如此结构化的对象数组。
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))
它是根据前两个字符排序的,而不是按照年、月、日、时和分正确排序。
有什么想法吗?我相信这很容易,但我很困惑。
答案 0 :(得分:2)
您可以创建一个 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; }
答案 1 :(得分:1)
您可以将 moment.Js
与公式 parse Date 一起使用
const parseDate = strDate => moment(strDate, "DD/MM/YYYY HH:mm");
之后,您可以通过类似的排序方法对数组进行排序
array.sort((a, b) => parseDate(a.date) - parseDate(b.date));
完整代码片段
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"}];
const parseDate = strDate => moment(strDate, "DD/MM/YYYY HH:mm");
array.sort((a, b) => parseDate(a.date) - parseDate(b.date));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
答案 2 :(得分:0)
首先可以通过三种方式执行此操作。如果日期在 DD/MM/YYYY,只需将它们转换为 YYYYMMDD
array.sort(function(date1,date2) {
date1 = date2.split('/').reverse().join('');
date1 = date2.split('/').reverse().join('');
return date1 > date2 ? 1 : date1 < date2 ? -1 : 0;
});
在第二种方法中你可以使用 String.prototype.localeCompare()
array.sort(function(date1, date2) {
return date1.localeCompare(date2);
})
第三个很容易失败,您可以将两者都转换为 Date 对象并进行比较