JSFiddle - React, Tailwind, and code Playground
by Abdul Ahmad
JavaScript
const data = [
{
"StudentID": "00001480",
"ModuleCode": "MED3007-N",
"AcYear": "2018/9",
"Mark": "80",
"Grade": "A"
},
{
"StudentID": "00001480",
"ModuleCode": "MED3020-N",
"AcYear": "2018/9",
"Mark": "82",
"Grade": "A"
}
];
const finalData = data.reduce((acc, d) => {
let student = acc[d.StudentID];
if (student) student = mergeStudents(student, d);
else student = d;
acc[d.StudentID] = student;
return acc;
}, {});
console.log('finaldata', finalData);
// student1 will always be the previously merged one
function mergeStudents(accumulatedStudent, newStudent) {
return Object.keys(accumulatedStudent).reduce((acc, key) => {
if (key === 'StudentID') acc[key] = accumulatedStudent[key];
else acc[key] = determineValue(accumulatedStudent, newStudent);
return acc;
}, {});
}
function determineValue(accumulatedStudent, newStudent) {
const accStudentValue = accumulatedStudent[key];
const newStudentValue = newStudent[key];
let finalValue;
if (valueAlreadyExists()) acc[key] = value;
else {
if (Array.isArray(value)) value.push(newStudent[key]);
else value = [value, newStudent[key]];
acc[key] = value;
}
}