I'm having difficulties combining two arrays of objects (retrieved from blockchain data) into a new array based on the values of the objects.
The aim is to extract the most recent interaction with a user.
A simplified yet closely resembling representation of the data structure where this issue arises:
interface MsgSlice {
messageId: string;
messageDataSlice: {
senderId?: string;
receiverId: string;
timestamp: number;
};
};
const latestReceivedMsgs: MsgSlice[] = [
{
messageId: "messageId1",
messageDataSlice: {
senderId: "userId1",
receiverId: "ownerId", // <- always same in that array
timestamp: 101,
},
},
{
messageId: "messageId3",
messageDataSlice: {
senderId: "userId2",
receiverId: "ownerId",
timestamp: 103,
},
},
{
messageId: "messageId5",
messageDataSlice: {
senderId: "userId3",
receiverId: "ownerId",
timestamp: 105,
},
},
];
const latestSentMsgs: MsgSlice[] = [
{
messageId: "messageId2",
messageDataSlice: {
// senderId: "ownerId",
receiverId: "userId1",
timestamp: 102,
},
},
{
messageId: "messageId4",
messageDataSlice: {
receiverId: "userId3",
timestamp: 104,
},
},
];
The expected outcome should include the newest messageId either 'sent to' or 'received by' the respective user. Something like this:
const latestInteraction = [
{
user: "userId1",
messageId: "messageId2",
timestamp: 102,
},
{
user: "userId2",
messageId: "messageId3",
timestamp: 103,
},
{
user: "userId3",
messageId: "messageId5",
timestamp: 105,
},
]
To address this, my initial approach was to iterate over the arrays and within each iteration, also go through the other array to compare the senderId
and receiverId
values. If "senderId
is == one of the iterated receiverId
s", it could be included in an interaction
array, which can then be sorted chronologically and filtered. However, I struggled to make this method work effectively. Perhaps my thinking is constrained here, and there are likely more efficient methods to achieve this task than what I initially proposed.