问题描述
我正在使用 sort()按日期对数组进行排序
I´m using sort() to order an Array by date
elements = data.sort(function(a, b) {
return a.date.getTime() - b.date.getTime()
});
问题是某些元素缺少日期(或日期无效)并导致此错误:
the problem is that some elements are missing the date (or the date is invalid)and that´s causing this error:
无法读取未定义
Cannot read property 'getTime' of undefined
更新:我已经准备好使用
update: I have moment ready to use
我应该在哪里检查日期是否为有效日期,然后使用它对数组进行排序?
Where should I check if date is valid date and then use it to order the array?
更新:这是我的数据
[{
"date": "2019-06-15 14:57:13",
"user": "john"
},
{
"date": "2019-06-15 05:48:01",
"user": "mike"
},
{
"date": "bad-date-format",
"user": "donna"
},
{
"date": "2019-06-08 10:45:09",
"user": "Ismil"
},
{
"date": "",
"user": "Daniel17"
}
]
这是我期望的输出
[
{
"date": "2019-06-15 14:57:13",
"user": "john"
},
{
"date": "2019-06-15 05:48:01",
"user": "mike"
},
{
"date": "2019-06-08 10:45:09",
"user": "Ismil"
},
{
"date": "bad-date-format",
"user": "donna"
},
{
"date": "",
"user": "Daniel17"
}
]
推荐答案
您不必检查字符串是否为有效日期.
You don't have to check if the string is a valid date.
这是一个有效的代码:
const data = [{
"date": "2019-06-15 14:57:13",
"user": "john"
},
{
"date": "2019-06-15 05:48:01",
"user": "mike"
},
{
"date": "bad-date-format",
"user": "donna"
},
{
"date": "2019-06-08 10:45:09",
"user": "Ismil"
},
{
"date": "",
"user": "Daniel17"
}
];
const elements = data.sort((a, b) => (new Date(b.date).getTime() || -Infinity) - (new Date(a.date).getTime() || -Infinity));
console.log(elements);
上面代码背后的技巧是,如果您向其传递无效的日期字符串,则 new Date()
将给出一个 Invalid Date
对象,该对象将返回 NaN
,如果您执行其 getTime()
方法.
The trick behind the above code is that new Date()
will give an Invalid Date
object if you pass an invalid date string to it, which will return NaN
if you executed its getTime()
method.
现在,因为您希望所有 Invalid Date
s都位于底部,因此排序功能应将这些 Invalid Date
s视为数组中评分最低的,并且这就是 -Infinite
的含义(最低编号.如果向其中添加任何数字,将导致 -Infinite
).
Now because you want all Invalid Date
s to be at the bottom, then your sorting function should treat these Invalid Date
s as the lowest rated in your array, and that's what -Infinite
means (the lowest number. If you add any number to it will lead to -Infinite
).
我认为对数组底部的 Invalid Date
进行排序并不重要.
I assume that it doesn't matter how Invalid Date
s are sorted at the bottom of your array.
这篇关于在Javascript中按日期对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!