-2

With An example, I'm basically trying to go from :

   [  
   {  
      'a':a1,
      'b':b2
   },
   {  
      'a':a1,
      'b':b5
   },
   {  
      'a':a3,
      'b':b4
   }
]

To :

 [  
   {  
      'group':'a1',
      'content':[  
         {  
            'a':a1,
            'b':b2
         },
         {  
            'a':a1,
            'b':b5
         }
      ],

   },
   {  
      'group':'a3',
      'content':[  
         {  
            'a':a3,
            'b':b4
         }
      ]
   }
]

So in word reformat the array and group elements on an attribute, here a

An-droid
  • 6,433
  • 9
  • 48
  • 93
  • 3
    right, where is the problem? – Nina Scholz Mar 15 '18 at 15:47
  • 1
    Use the `Array.prototype.reduce` function, and come back if you have an issue. We're not here to make your work. –  Mar 15 '18 at 15:50
  • Possible duplicate of [What is the most efficient method to groupby on a JavaScript array of objects?](https://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – Andreas Mar 15 '18 at 15:58
  • If you cant add 3rd party libraries, i suggest you to go with native javascript `reduce` – Leonardo Lima Mar 16 '18 at 16:25

2 Answers2

1

There is a simple way by using lodash GroupBy

https://lodash.com/docs#groupBy

_.groupBy([
  {  
    'a':"a1",
    'b':"b2"
  },
  {  
    'a':"a1",
    'b':"b5"
  },
  {  
    'a':"a3",
    'b':"b4"
  }
 ], "a")

The first arguments the array you want to group, an the second is the iterator you want to group, the result will be grouped in a array, it will not have the content preoperty.

{
   "a1":[
      {
         "a":"a1",
         "b":"b2"
      },
      {
         "a":"a1",
         "b":"b5"
      }
   ],
   "a3":[
      {
        "a":"a3",
        "b":"b4"
      }
   ]
}

See if this helps get you going, if not, let me know

Leonardo Lima
  • 130
  • 10
  • I really need to separate the group name and the content to access is easily in pipe as in my example – An-droid Mar 20 '18 at 10:47
0

If you only want that grouped array then you can achieve using reducer.

`let group = data.reduce((r, a) => {
 r[a.a] = [...r[a.a] || [], a];
 return r;
 }, {});`

var data =   [  
   {  
      'a':'a1',
      'b':'b2'
   },
   {  
      'a':'a1',
      'b':'b5'
   },
   {  
      'a':'a3',
      'b':'b4'
   }
]
let group = data.reduce((r, a) => {
 r[a.a] = [...r[a.a] || [], a];
 return r;
}, {});
console.log("group", group);