如何映射按所需对象值分组的嵌套数组的数组

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);