Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* You are given a list of students score given as text table with the following columns:
- student name, course, grade, number of visits. A student can have several grades and visits
- for the same course. Write a JavaScript function to aggregate the results and print then as JSON string.
- The input is passed as array of strings holding the table lines. Print at the console a JSON string
- that holds the courses (in alphabetical order), the average grade and average visits for each course
- and a list of students for each course (in alphabetical order). Duplicates should be removed
- (all strings are case-sensitive). Please follow exactly the JSON format from the example below.
- The average numbers should be rounded to 2 digits after the decimal point and printed without
- trailing zeroes. */
- "use strict";
- function aggregateStudentsResults(arr) {
- var dataMap = {};
- for (var i = 0; i < args.length; i += 1) {
- var studentData, student, course, grade, visits;
- studentData = args[i].split(/\|/).filter(Boolean);
- student = studentData[0].trim();
- course = studentData[1].trim();
- grade = parseFloat(studentData[2]);
- visits = parseFloat(studentData[3]);
- if (!(dataMap.hasOwnProperty(course))) {
- dataMap[course] = { 'avgGrade': [], 'avgVisits': [], 'students': [] };
- }
- dataMap[course].avgGrade.push(grade);
- dataMap[course].avgVisits.push(visits);
- if (dataMap[course].students.indexOf(student) < 0) {
- dataMap[course].students.push(student);
- }
- }
- function getAverageNumber(arr) {
- var sum = 0;
- arr.forEach(function (num) {
- sum += num;
- });
- return Number((sum / arr.length).toFixed(2));
- }
- function sortingObject(object) {
- var sortedKeys = Object.keys(object).sort();
- var newOject = {};
- for (var i = 0; i < sortedKeys.length; i += 1) {
- if (object.hasOwnProperty(sortedKeys[i])) {
- newOject[sortedKeys[i]] = {};
- newOject[sortedKeys[i]].avgGrade = getAverageNumber(object[sortedKeys[i]].avgGrade);
- newOject[sortedKeys[i]].avgVisits = getAverageNumber(object[sortedKeys[i]].avgVisits);
- newOject[sortedKeys[i]].students = object[sortedKeys[i]].students.sort();
- }
- }
- return newOject;
- }
- dataMap = sortingObject(dataMap);
- console.log(JSON.stringify(dataMap));
- }
- aggregateStudentsResults([
- 'Peter Nikolov | PHP | 5.50 | 8',
- 'Maria Ivanova | Java | 5.83 | 7',
- 'Ivan Petrov | PHP | 3.00 | 2',
- 'Ivan Petrov | C# | 3.00 | 2',
- 'Peter Nikolov | C# | 5.50 | 8',
- 'Maria Ivanova | C# | 5.83 | 7',
- 'Ivan Petrov | C# | 4.12 | 5',
- 'Ivan Petrov | PHP | 3.10 | 2',
- 'Peter Nikolov | Java | 6.00 | 9'
- ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement