I have this array of message objects and I wanted to group them that have similar from - to value or vice versa.
const msgs = [
{ id: '1', from: 'mimi', to: 'gudo', createdAt: '2021-01-01:T-50-249' }, //GROUP THIS
{ id: '5', from: 'gudo', to: 'mimi', createdAt: '2021-01-01:T-46-462' }, //
{ id: '2', from: 'john', to: 'gudo', createdAt: '2021-01-01:T-50-249' }, //GROUP THIS
{ id: '3', from: 'gudo', to: 'john', createdAt: '2021-01-01:T-46-462' }, //
{ id: '7', from: 'dave', to: 'gudo', createdAt: '2021-01-05' }, //GROUP THIS
]
This is my take to this, but there's still a problem, I have no clue how to append the obj that has no pair which is the object that has from property value of dave
let msg = [
{ id: '2', from: 'mimi', to: 'gudo', createdAt: '2021-01-01'},
{ id: '3', from: 'gudo', to: 'mimi', createdAt: '2021-01-02' },
{ id: '5', from: 'gudo', to: 'john', createdAt: '2021-01-03' },
{ id: '4', from: 'john', to: 'gudo', createdAt: '2021-01-05' },
{ id: '7', from: 'dave', to: 'gudo', createdAt: '2021-01-05' },
]
const sent = msg.filter(i => i.from === 'gudo');
const received = msg.filter(i => i.to === 'gudo');
const res = [];
for (let i = 0; i < sent.length; i++) {
const curMine = sent[i];
const pair = [];
for (let j = 0; j < received.length; j++) {
const curFrom = received[j];
if(curMine.to === curFrom.from) {
pair.push(curMine);
pair.push(curFrom);
}
}
res.push(pair);
}
console.log(res)
Expected output:
[
[
{ id: '2', from: 'mimi', to: 'gudo', createdAt: '2021-01-01'},
{ id: '3', from: 'gudo', to: 'mimi', createdAt: '2021-01-02' },
],
[
{ id: '5', from: 'gudo', to: 'john', createdAt: '2021-01-03' },
{ id: '4', from: 'john', to: 'gudo', createdAt: '2021-01-05' },
],
[
{ id: '7', from: 'dave', to: 'gudo', createdAt: '2021-01-05' }, // How to include this?
]
]
]
If you could help me or give an idea of a better way of doing this, I would be very grateful.