Group by JavaScript Array Object

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an array of arrays that contains the marks of some students in some subjects like this −

const arr = [ ["English", 52], ["Hindi", 154], ["Hindi", 241], ["Spanish", 10], ["French", 65], ["German", 98], ["Russian", 10] ];

We are required to write a JavaScript function that takes in one such array and returns an object of objects.

The return object should contain an object for each unique subject, and that object should contain information like the number of appearances of that language, sum of total marks and the average.

Example

The code for this will be −

const arr = [
   ["English", 52],
   ["Hindi", 154],
   ["Hindi", 241],
   ["Spanish", 10],
   ["French", 65],
   ["German", 98],
   ["Russian", 10]
];
const groupSubjects = arr => {
   const grouped = arr.reduce((acc, val) => {
      const [key, total] = val;
      if(!acc.hasOwnProperty(key)){
         acc[key] = {
            'count': 0,
            'total': 0
         };
      };
      const accuKey = acc[key];
      accuKey['count']++;
      accuKey['total'] += total;
      accuKey['average'] = total / accuKey['count'];
      return acc;
   }, {});
   return grouped;
};
console.log(groupSubjects(arr));

Output

And the output in the console will be −

{
English: { count: 1, total: 52, average: 52 },
Hindi: { count: 2, total: 395, average: 120.5 },
Spanish: { count: 1, total: 10, average: 10 },
French: { count: 1, total: 65, average: 65 },
German: { count: 1, total: 98, average: 98 },
Russian: { count: 1, total: 10, average: 10 }
}
raja
Published on 21-Nov-2020 10:09:14
Advertisements