简体   繁体   中英

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 .

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.

Javascript implementation with Array.reduce and 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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