Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mapping two arrays to create one array

I have two arrays which id like to merge into one array, however, the arrays have some complexities which I can’t wrap my head around…. In short, I have an array of "last message" from a conversation, and I have an array of participants from that conversation.

The "messages" array looks like this

messageArray =
[
  [
    { message } <=== convo 1
  ],
  [
    { message } <===  convo 2
  ],
]

The "participant" data array looks like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

participantArray = 
[
   [
     {participant},{participant} <=== participants in convo 1
   ],
   [
     {participant},{participant},{participant} <=== participants in convo 2
   ]
]

What i’d like to have is

mergedArray =
[
  [ { message }, [ { participant }, { participant  } ]] <=== conversation 1
],
[
  [ { message }, [ { participant }, { participant  } ]] <=== conversation 2
]

>Solution :

Based on your description, you can map the first array, and use the index to get the associated items in the second array.

eg.

const messages = [
  ["Helo World, Messsage One"],
  ["Goodbye, fair well"],
];

const users = [
   ["Bob", "Jane", "Harry"],
   ["Mike", "John", "Amanda"]
];

const joined = messages.map((m, ix) => {
  return [m[0], users[ix]];
});

console.log(joined);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading