Home > Software design >  Combine 2 arrays based on their common id
Combine 2 arrays based on their common id

Time:10-03

I have 2 different arrays, that i want to combine. The first one looks like following:

const Cats[] = [
  { id: '1', name: 'Smiley' },
  { id: '2', name: 'Purple' },
]

the second one:

  const catAges[] = [
    { id: '4', age: '13', catId: '1' },
    { id: '5', age: '4', catId: '2' },
  ];

and i want to combine them where id from Cats[] and catId from catAges[] are the same and have a result like following:

  { id: '4', age: '13', cat: { id: '1', name: 'Smiley' } },
  { id: '5', age: '4', cat: { id: '2', name: 'Purple' } },

i get the arrays from 2 different async functions looking like this:

const cats = [await getByCatId("1"), await getByCatId("2")];

const catsAge = await getCatsAges();

But i need help in how i combine these 2 and map them. I've tried something like this but without any success:

const all = (cats, catsAge) =>
cats.map(cats=> ({
    ...catsAge.find((cats) => (catsAge.catId === cats.id) && catsAge),
    ...cats
}));
console.log(all(cats, catsAge));

Thankful for any help in how to move forward.

CodePudding user response:

const Cats = [
  { id: '1', name: 'Smiley' },
  { id: '2', name: 'Purple' },
]

const catAges = [
  { id: '4', age: '13', catId: '1' },
  { id: '5', age: '4', catId: '2' },
];

const transformed = catAges.map(item => {
  const cat = Cats.find(cat => cat.id === item.catId);
  
  if (cat) {
    item.cat = cat;
    delete item.catId;
  }
  
  return item;
});

console.log(transformed);

CodePudding user response:

The problem with your function is just that you're re-using the cats variable too much, so in your .find comparision you're comparing an element from catsAge (as cats.id) and the catsAge array (as catsAge.catId) which is undefined.

Try this:

const all = (cats, catsAge) =>
  cats.map((cat) => ({
    ...catsAge.find((catsAge) => catsAge.catId === cat.id),
    ...cat,
  }));

Pro tip: Learn Use Typescript and the compiler would catch these errors for you :)

CodePudding user response:

const Cats = [
      { id: '1', name: 'Smiley' },
      { id: '2', name: 'Purple' },
    ]

const catAges = [
    { id: '4', age: '13', catId: '1' },
    { id: '5', age: '4', catId: '2' },
  ];

catAges.map(catage => {
  const cat = Cats.find(c => c.id == catage.catId);
  if(cat) {
        delete catage.catId;
        catage.cat = cat;
        return catage;
    }
});
  • Related