【发布时间】:2018-07-16 14:54:53
【问题描述】:
希望你能帮助我解决这个问题,我很确定它很简单,但我觉得我在这里缺少一些基本概念。
我有一个对象数组,比如
[{
"id":"123",
"creationUser":"user1",
"updateUser":null,
"creationDate":1517495569000,
"updateDate":null,
"text":"Hello World"
},
{
"id":"543",
"creationUser":"user2",
"updateUser":"user3",
"creationDate":1517912985769,
"updateDate":1517921704448,
"text":"Hello people"
},
{
"id":"847",
"creationUser":"user 4",
"updateUser":null,
"creationDate":null,
"updateDate":1517913015110,
"text":"Text 1"
},
{
"id":"344",
"creationUser":"user 1",
"updateUser":"central",
"creationDate":1517912979283,
"updateDate":1517923926834,
"text":"Aloha!"
}]
如您所见,有些对象尚未更新,因此这些值设置为 null,但其他值已更新,所以我想做的是按创建日期对该数组进行排序,除非它有已更新,也就是说updatedDate是比较这个数组的key值。
我试过了:
let comments = conversation.sort(
(a,b) => {
if (a.updateDate){
return (a.creationDate - b.updateDate);
} else {
return (b.creationDate - a.updateDate);
}
});
但显然它只在比较未更新的对象时才有效。我很确定我遗漏了一些东西,但我不确定,我还考虑将数组拆分为更新数组和未更新数组,然后合并它,但这对我来说听起来有点 hacky。
拜托,如果你能给我一个提示,那就太好了!
非常感谢!
【问题讨论】:
-
好吧,你有一个错误:
conversation.sort((a, b) => {缺少=>。 -
true @Andy,已编辑!谢谢
标签: javascript arrays sorting ecmascript-6