Search code examples
javascriptarraysjavascript-objects

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.


Solution

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