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

Merge 3 arrays by matching ID's

I have a small exercise, to merge three arrays into one array by matching ID’s, I’d like to add the likes and comments array into the posts array how would I go about this?

const posts = 
  [ { _id: 1
    , message: 'this is post one'
    , likes:    [ { id: 1111 } , { id: 2222 } ] 
    , comments: [ { id: 3333 } , { id: 4444 } ] 
    } 
  ] 
const comments = 
  [ { id: 3333, message: 'this is comment 1' } 
  , { id: 4444, message: 'this is comment 2' } 
  ] 
const likes = 
  [ { id: 1111, user: 'Peter' } 
  , { id: 2222, user: 'John'  } 
  ] 

expected output:

newArray = 
  [ { _id: 1
    , message: 'this is post one'
    , likes: 
      [ { id: 1111, user: 'Peter'} 
      , { id: 2222, user: 'John'} ] 
    , comments: 
      [ { id: 3333, message: 'this is comment 1'} 
      , { id: 4444, message: 'this is comment 2'} 
  ] } ] 

Here is a similar approach I’ve used when working with two arrays:

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

const
  arr1 = [{ groupId: "Category", options: [{ name: "cookies", id: 1111 }, { name: "tv", id: 2222 }] }, { groupId: "Brand", options: [{ name: "random", id: 3333 }] }, { groupId: "Price", options: [{ name: "random2", id: 4444 }] }],
  arr2 = [{ id: 1111, url: "/test", other: 'other-prop' }, { id: 2222, url: "/test1" }, { id: 3333, url: "/test2" }],

  mergeById = (arr1, arr2) =>
    arr1.map(({ options, ...rest }) => (
      {
        ...rest,
        options: options.map(option => (
          {
            ...option,
            ...arr2.find(_option => _option.id === option.id)
          }
        ))
      }
    ));

const merged = mergeById(arr1, arr2);

console.log(JSON.stringify(merged, null, 2));

>Solution :

const newPosts = posts.map(post => ({
    ...post,
    likes: likes.filter(like => post.likes.map(like => like.id).includes(like.id)),
    comments: comments.filter(comment => post.comments.map(comment => comment.id).includes(comment.id)),
}))

console.log(newPosts)
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