Aymen Kanzari
Aymen Kanzari

Reputation: 2013

typescript: custom groupBy in array

I have the below array

[
 {
   "exam" : "1",
   "class": "1A1",
   "rooms": "245",
   "teachers": "A"
 },
 {
   "exam" : "1",
   "class": "1A2",
   "rooms": "685",
   "teachers": "B"
 },
 {
   "exam" : "2",
   "class": "1EM1",
   "rooms": "630",
   "teachers": "C"
 }
]

How can i convert it in this format ? i tried with groupBy from lodash but i don't get a good result.

[
 {
   "exam" : "1",
   "classes": [
     {
       "class": "1A1",
       "rooms": "245",
       "teachers": "A"
     },
     {
       "class": "1A2",
       "rooms": "685",
       "teachers": "B"
     }
   ]
 },
 {
   "exam" : "2",
   "classes": [
     {
       "class": "1EM1",
       "rooms": "630",
       "teachers": "C"
     }
   ]
 } 
]

Upvotes: 0

Views: 125

Answers (1)

Yogesh G
Yogesh G

Reputation: 1160

var data = [
 {
   "exam" : "1",
   "class": "1A1",
   "rooms": "245",
   "teachers": "A"
 },
 {
   "exam" : "1",
   "class": "1A2",
   "rooms": "685",
   "teachers": "B"
 },
 {
   "exam" : "2",
   "class": "1EM1",
   "rooms": "630",
   "teachers": "C"
 }
];

// Take a blank object as accumuator and add various class objects grouped by examId.
const classDataByExams = data.reduce((acc, x) => {
    // Split object with exam key and the remaining keys on data object.
    const {exam, ...classData} = x;
    // Add the examId in accumuator if not present and then push the classData from above.
    (acc[x.exam] = acc[x.exam] || []).push(classData);
    return acc;
}, {});

// Convert the object to the array format.
console.log(Object.keys(classDataByExams).map(x => ({'exam': x, 'classes': classDataByExams[x]})));

enter image description here

Upvotes: 1

Related Questions