繁体   English   中英

如何 map 按所需 object 值分组的嵌套 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 },
]

我有所有的消息,但它们没有按用户对用户的对话分组。 我想要的是通过tofrom对消息(在数组内)进行分组。

我怎样才能达到以下结果:

[
  [
    { 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.reduceArray.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM