Home > Enterprise >  Move objects in array where duplicates occur
Move objects in array where duplicates occur

Time:08-19

I have an array of objects, each array has a key of name and then another array of objects:

const myArray = [ { name: "1", item: [{}] }, { name: "2", item: [{}] }, { name: "1", item: [{}] } ]

Now for example sometimes that name key will be the same, i want to be able to check if that name exists and if it does exist push the item into that array object and not into a new object.

The behaviour im getting is above but i would like:

const myArray = [ { name: "1", item: [{ item1, item2 etc }] }, { name: "2", item: [{}] }, { name: "3", item: [{}] } ]

Thanks so much in advance!

CodePudding user response:

You can get the desired result using Array.reduce(), grouping by name.

If two objects in myArray share the same name, the item values are combined.

const myArray = [ { name: "1", item: [{ id: 1 }] }, { name: "2", item: [{ id: 2}] }, { name: "1", item: [{ id: 3}] } ]

const result = Object.values(myArray.reduce((acc, { name, item }) => { 
    acc[name] = acc[name] || { name, item: [] };
    acc[name].item.push(...item);
    return acc;
}, {}))

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

CodePudding user response:

Here's a solution using Array.prototype.reduce function.

const myArray = [ { name: "1", item: [{}] }, { name: "2", item: [{}] }, { name: "1", item: [{}] } ];

const output = myArray.reduce((acc, curr) => {
  const index = acc.findIndex(pre => pre.name === curr.name);
  if(index !== -1) {
    acc[index].item = acc[index].item.concat(curr.item);
  } else {
    acc.push(curr);
  }
  
  return acc;
}, []);

console.log(output);

  • Related