-1

How to transform this items array to result array (objects should be with unique id and have key 'names' with array of name properties from objects with the same id):

Original array:

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

Transformed array:

const result = [
{id: 1, names: ['a', 'd']}, 
{id: 2, names ['b']}, 
{id: 3, names: ['c', 'f']}
];
jslearner
  • 11
  • 2
  • 1
    Does this answer your question? [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) – User863 Oct 07 '21 at 10:55

1 Answers1

1

You can use Array.reduce to get the result.

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

const result = inputArray.reduce((acc, item) => {
   const exist = acc.find(e => e.id == item.id);
   // check exist in result
   if (exist) {
      // exist: push 'name' value to 'names' array
      exist['names'].push(item.name);
   } else {
      // not exist: create new item in result
      acc.push({
         'id': item.id,
         'names': [item.name]
      });
   }
   
   return acc;
}, []);

console.log(result);
Tuan Dao
  • 2,647
  • 1
  • 10
  • 20