[英]How to map an array of nested arrays grouped by desired object values
I have an array of messages which are like the following:我有一组消息,如下所示:
[
{ message: 'This is message', to: 4, from: 1},
{ message: 'This is response message', to: 1, from: 4 },
{ message: 'This is ANOTHER message with different sender', to: 1, from: 2 },
{ message: 'This is RESPONSE message to different sender', to: 2, from: 1 },
]
I have all the messages, but they are not grouped by the user-to-user conversation.我有所有的消息,但它们没有按用户对用户的对话分组。 What I want is to group the messages (inside an array) by
to
and from
.我想要的是通过
to
和from
对消息(在数组内)进行分组。
How can I achieve the following outcome:我怎样才能达到以下结果:
[
[
{ message: 'This is message', to: 4, from: 1},
{ message: 'This is response message', to: 1, from: 4 },
],
[
{ message: 'This is ANOTHER message with different sender', to: 1, from: 2 },
{ message: 'This is RESPONSE message to different sender', to: 2, from: 1 }
],
]
In short:简而言之:
Current structure is目前的结构是
// Individually structured messages
[message, message, message, message]
Desired outcome:期望的结果:
// Grouped by user-to-user conversation
// [[Conversation1], [Conversation2]]
[[message, message], [message,message]]
I have tried using lodash with return this._.values(this._.groupBy(this.messages, 'to'))
, but since I need to group them by two criteria, I didn't manage to come up with the logic.我曾尝试将 lodash 与
return this._.values(this._.groupBy(this.messages, 'to'))
,但由于我需要按两个标准对它们进行分组,所以我没能想出逻辑。
Javascript implementation with Array.reduce
and Array.find
Javascript 使用
Array.reduce
和Array.find
实现
const messages = [ { message: 'This is message', to: 4, from: 1}, { message: 'This is response message', to: 1, from: 4 }, { message: 'This is ANOTHER message with different sender', to: 1, from: 2 }, { message: 'This is RESPONSE message to different sender', to: 2, from: 1 }, ]; const groupedMessage = messages.reduce((acc, curr) => { const node = acc.find(item => item.find((msg) => (msg.from === curr.to && msg.to === curr.from) || (msg.from === curr.from && msg.to === curr.to))); node? node.push(curr): acc.push([curr]); return acc; }, []); console.log(groupedMessage);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.