【发布时间】:2018-10-25 08:56:44
【问题描述】:
我的数组对象如下例所示。
list = [
{'name': 'test1', 'email': 'test1@gmail.com', 'ispin': true, 'updatedAt': 1540456416646}
{'name': 'test2', 'email': 'test2@gmail.com', 'ispin': false, 'updatedAt': 1540456416111}
{'name': 'test3', 'email': 'test3@gmail.com', 'ispin': true, 'updatedAt': 1540456412541}
{'name': 'test4', 'email': 'test4@gmail.com', 'ispin': false, 'updatedAt': 1540456414521}
]
我可以像这样对这个数组对象进行排序。
return conversationList.sort((a, b) => {
const firstTimestamp = a.lastMessage && a.lastMessage.createdAt ? a.lastMessage.createdAt : 0;
const secondTimestamp = b.lastMessage && b.lastMessage.createdAt ? b.lastMessage.createdAt : 0;
//Sort in DESC order
return secondTimestamp - firstTimestamp;
});
使用上面的代码,我可以按降序对对象数组进行排序。
现在,我的要求是首先基于 ispin 键的过滤器数组。 如果 ispin 设置为 true,那么我想创建新的数组对象,键 pin 也在降序order 和一个数组,键为 recent 以降序排列。
所以我的最终输出应该是这样的。
{
// first array object with key pin : filter by ispin:true and order by descending order
pin: [
{'name': 'test1', 'email': 'test1@gmail.com', 'ispin': true, 'updatedAt': 1540456416646}
{'name': 'test3', 'email': 'test3@gmail.com', 'ispin': true, 'updatedAt': 1540456412541}
],
// second array object with ket recent : order by descending order and records which has ispin false
recent: [
{'name': 'test2', 'email': 'test2@gmail.com', 'ispin': false, 'updatedAt': 1540456416111}
{'name': 'test4', 'email': 'test4@gmail.com', 'ispin': false, 'updatedAt': 1540456414521}
]
}
【问题讨论】:
-
我相信你可以通过
.reduce()方法实现这一点。您可以创建一个包含具有isPin:true的对象的新数组,然后像之前那样对该数组进行排序。 -
@T.J.Crowder :我不认为这个副本是一个好的副本。当您关闭问题时,我正在写一个答案,该问题具有 groupBy 功能(使用 reduce 作为另一条提到的评论)。 OP 在这里需要分组,而不是过滤,这个问题的答案比重复目标要好得多。
-
啊,对,我认为这毫无意义(并且在查看我的答案时才意识到)。应该是
{ pin: [{}] }
标签: javascript arrays sorting filter grouping