-1

I have an array of object something like this, can i get a solution based on JavaScript?

example:

input:

 [
{id:'user1', class: 3, key: 'aaa1'},
{id:'user2', class: 4, key: 'aaa1'},
{id:'user1', class: 3, key: 'ccc1'},
{id:'user3', class: 5, key: 'aaa1'}
]

expecting the below output

 [
{id:'user1', class: 3, key:[ 'aaa1', 'ccc1']},
{id:'user2', class: 9, key: 'aaa1'},
{id:'user3', class: 5, key: 'aaa1'}
]`

Expecting optimized solution for this problem

pilchard
  • 12,414
  • 5
  • 11
  • 23
Varun
  • 11
  • 3
  • Is the class property functional dependent on the id property? – trincot May 02 '23 at 22:02
  • [Most efficient method to groupby on an array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects), [How can I group an array of objects by key?](https://stackoverflow.com/questions/40774697/how-can-i-group-an-array-of-objects-by-key) or for multiple keys [Group objects by multiple properties in array then sum up their values](https://stackoverflow.com/questions/46794232/group-objects-by-multiple-properties-in-array-then-sum-up-their-values) – pilchard May 02 '23 at 22:14

1 Answers1

0

I've used Array#reduce to solve this problem:

const input = [
  { id: "user1", Class: 3, key: "aaa1" },
  { id: "user2", Class: 4, key: "aaa1" },
  { id: "user1", Class: 3, key: "ccc1" },
  { id: "user3", Class: 5, key: "aaa1" },
];
const output = Object.values(
  input.reduce((acc, { id, Class, key }) => {
    if (!acc[id]) {
      acc[id] = {id, Class, key};
    } else if (acc[id].Class === Class) {
      acc[id].key = [acc[id].key, key];
    }
    return acc;
  }, {})
);

console.log(output);

P.S: avoid using reserved keywords by JS like class, I replaced with Class capital C.
P.P.S: Your expecting output is errorned in user2 class must be 4 not 9.

XMehdi01
  • 5,538
  • 2
  • 10
  • 34