![](/img/trans.png)
[英]Sum values of array of object grouped by keys and return into a new array of arrays
[英]How to map an array of nested arrays grouped by desired object values
我有一組消息,如下所示:
[
{ 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 },
]
我有所有的消息,但它們沒有按用戶對用戶的對話分組。 我想要的是通過to
和from
對消息(在數組內)進行分組。
我怎樣才能達到以下結果:
[
[
{ 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 }
],
]
簡而言之:
目前的結構是
// Individually structured messages
[message, message, message, message]
期望的結果:
// Grouped by user-to-user conversation
// [[Conversation1], [Conversation2]]
[[message, message], [message,message]]
我曾嘗試將 lodash 與return this._.values(this._.groupBy(this.messages, 'to'))
,但由於我需要按兩個標准對它們進行分組,所以我沒能想出邏輯。
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.