Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

45
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!