0

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.

1

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

This works! Only thing is that I forgot to give an example that there is a case where the conversation is only 1 sided. For example: Hey Good morning! (to : 4, from 2) Are you there? (to : 4, from 2) Please answer? (to : 4, from 2)
@BerinAptula Updated the answert, please check.
This solved my challenge. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.