-1

For example, how can I turn the array of objects shown below into the corresponding result where names are grouped by id? I'd like to do this using vanilla Javascript and without using an external library like lodash if possible.

Example array:

const items = [
    { id: 1, name: 'a' },
    { id: 2, name: 'b' },
    { id: 3, name: 'c' },
    { id: 1, name: 'd' },
    { id: 3, name: 'f' },
    { id: 1, name: 'a' },
    { id: 3, name: 'c' },
  ];

Expected result:

 const result = [
   { id: 1, names: ['a', 'd']},
   { id: 2, names: ['b']},
   { id: 3, names: ['c', 'f']}
  ] 
jpierson
  • 16,435
  • 14
  • 105
  • 149
Jenny Le
  • 15
  • 3

1 Answers1

1

I'm performing an reduce on the array and it gives me an object in the form of

{
  1: [object Set] { ... },
  2: [object Set] { ... },
  3: [object Set] { ... }
}

where Set is used to keep unique values only.

After that I'm running a map on Object.entries to get the data to the format you wanted.

const items = [{ id: 1, name: 'a' },{ id: 2, name: 'b' },{ id: 3, name: 'c' },{ id: 1, name: 'd' },{ id: 3, name: 'f' },{ id: 1, name: 'a' },{ id: 3, name: 'c' },];
  
  const a = items.reduce((acc,curr)=> {
    if(!acc[curr.id]){
        acc[curr.id] = new Set();
    }
    
    acc[curr.id].add(curr.name)
   
    return acc;
  },{})
  
  let result = Object.entries(a).map((el) => ({id: el[0],names:[...el[1]]}))
  
  console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
cmgchess
  • 7,996
  • 37
  • 44
  • 62