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

Creating a function that compares 2 different arrays and passs down each matching pair into a component

I am trying to create a component that calls upon two arrays. The arrays are them mapped out and the pair that matches is send down through props into a child component. I am making a list component that calls said arrays from the back end and then sends down the information to a listItem component to be rendered. The arrays look something like this

const Stores = [
{
id: 1,
name: Store One,
},
{
id: 2,
name: Store Two,
},
]
const Users = [
{
id: 100,
name: User One,
storeId: 1,
},
{
id: 200,
name: User Two,
storeId: 1,
},
{
id: 300,
name: User Three,
storeId: 2,
},
{
id: 400,
name: User Four,
storeId: 2,
},
]

Currently i am just passing down the user information into the listItem component and using http requests on each item but as you can tell when the User or Stores list reaches 100+ items that the amount of http requests will bog down the app too much. What I thought of is just calling once in the List component and passing down each information that way it would be one call but cannot figure out the function required to acheive this. Is there anyone that can help me brainstorm?

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

>Solution :

const Stores = [{
    id: 1,
    name: 'Store One',
  },
  {
    id: 2,
    name: 'Store Two',
  },
]

const Users = [{
    id: 100,
    name: 'User One',
    storeId: 1,
  },
  {
    id: 200,
    name: 'User Two',
    storeId: 1,
  },
  {
    id: 300,
    name: 'User Three',
    storeId: 2,
  },
  {
    id: 400,
    name: 'User Four',
    storeId: 2,
  },
]

const grouped = Users.map(user => {
  // find store
  const store = Stores.find(store => store.id === user.storeId)
  // return grouped
  return {
    user: { ...user },
    store: { ...store }
  }
})

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