1

*Not the same as the flagged question. I don't just want to delete the duplicates; I want to consolidate the values of another property of the object to be removed.

For the following object:

orderedGroups: [ { parent: 'Components', subgroups: [ 'alphaselector' ] },
  { parent: 'Utilities', subgroups: [ 'colors' ] },
  { parent: 'Test Group', subgroups: [ 'component-test-alpha' ] },
  { parent: 'Document', subgroups: [ 'fixedtableheaders' ] },
  { parent: 'Utilities', subgroups: [ 'svgicons' ] },
  { parent: 'Utilities', subgroups: [ 'typography' ] } ]

How can I remove objects with duplicate parent entries while consolidating the corresponding subgroups?

Desired output:

orderedGroups: [ { parent: 'Components', subgroups: [ 'alphaselector' ] },
  { parent: 'Utilities', subgroups: [ 'colors', 'svgicons', 'typography' ] },
  { parent: 'Test Group', subgroups: [ 'component-test-alpha' ] },
  { parent: 'Document', subgroups: [ 'fixedtableheaders' ] } ]

What I have so far/where I'm stuck:

for (let val of Object.values(orderedGroups)) {

  if (orderedGroups.hasOwnProperty(val.parent)) {
    // remove duplicate objects and consolidate corresponding subgroups 
  }

}

*Note: I cannot import modules; must be plain js.

0

2 Answers 2

2

Dominic has a more elegant solution, but here's a simpler solution that might be easier for some to understand.

let output = [];

for(group of orderedGroups){
  let i;
  for(i=0;i<output.length;i++){
    if(output[i].parent===group.parent) break;
  }
  if(i===output.length){
    output.push(group);
  } else {
    output[i].subgroups=output[i].subgroups.concat(group.subgroups);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Map to store subgroups by key (in this case parent) and then only use for loop to add them to orderedGroups as you wish.

let orderedGroups = [ { parent: 'Components', subgroups: [ 'alphaselector' ] },
  { parent: 'Utilities', subgroups: [ 'colors' ] },
  { parent: 'Test Group', subgroups: [ 'component-test-alpha' ] },
  { parent: 'Document', subgroups: [ 'fixedtableheaders' ] },
  { parent: 'Utilities', subgroups: [ 'svgicons' ] },
  { parent: 'Utilities', subgroups: [ 'typography' ] } ]
  
let tmp = new Map()
for(let obj of orderedGroups) {
  if(tmp.has(obj.parent)) tmp.set(obj.parent, [...tmp.get(obj.parent), ...obj.subgroups])
  else tmp.set(obj.parent, [...obj.subgroups])
}
orderedGroups = [] 
for(let obj of tmp) {
  orderedGroups = [...orderedGroups, {parent: obj[0], subgroups: obj[1]}]
}
console.log(orderedGroups)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.