- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Group by JavaScript Array Object
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 } }
- Related Articles
- Group array by equal values JavaScript
- Group by element in array JavaScript
- Manipulate Object to group based on Array Object List in JavaScript
- Group values in array by two properties JavaScript
- JavaScript group a JSON object by two properties and count
- JSON group object in JavaScript
- Group a JavaScript Array
- How to group array of objects by Id in JavaScript?
- Sorting JavaScript object by length of array properties.
- How to group an array of objects by key in JavaScript
- Converting array to object by splitting the properties - JavaScript
- Merge and group object properties in JavaScript
- Sorting an array object by property having falsy value - JavaScript
- Object to array - JavaScript
- Group objects by property in JavaScript

Advertisements