0

I have an array of objects like this.

[
   {
      NAME: 'TEST_1',
      ORG: 'A',
      FROM: '20191223',
      TO: '99991231'
    },

   {
      NAME: 'TEST_1',
      ORG: 'B',
      FROM: '20191223',
      TO: '99991231'
   },

   {
      NAME: 'TEST_2',
      ORG: 'C',
      FROM: '20191223',
      TO: '99991231'
   },
   {
      NAME: 'TEST_2',
      ORG: 'D',
      FROM: '20191223',
      TO: '99991231'
   }
]

I want to group the array of objects by NAME and push the ORG in an array.

[
   {
      NAME: 'TEST_1',
      ORG: ['A', 'B']
      FROM: '20191223',
      TO: '99991231'
   },
      {
      NAME: 'TEST_1',
      ORG: ['C', 'D']
      FROM: '20191223',
      TO: '99991231'
   }
 ]

I tried to use the reduce function but it does not give me the desired results.

let group = this.myObj.reduce((r, a) => {

  r[a.NAME] = [...r[a.NAME] || [], a];
  return r;
}, {});
console.log("group", group);
user2281858
  • 1,957
  • 10
  • 41
  • 82
  • `enter code here` is a typo, please edit and remove it – caramba Feb 10 '20 at 14:49
  • What you actually mean is group by `NAME`, `FROM` and `TO`.... right? – Jamiec Feb 10 '20 at 14:54
  • @Jamiec, group by `NAME` since FROM and TO wont change. – user2281858 Feb 10 '20 at 14:55
  • That's exactly my point, unless you include them in the grouping, you'll get an array of them too. – Jamiec Feb 10 '20 at 14:56
  • obs.filter( e => e.NAME == name).reduce((a,b)=> (a.ORG = [...a.ORG, b.ORG], a)) – QuentinUK Feb 10 '20 at 15:03
  • Think this is a duplicate similar to https://stackoverflow.com/questions/8837454/sort-array-of-objects-by-single-key-with-date-value/31846142. You basically need to use the Array.sort function, which takes a comparison function as parameter. That link should help I think. – feyd Feb 10 '20 at 15:04

0 Answers0