score:3

Accepted answer

var input=[{student:"Alex",subject:"maths",marks:"85",answer:"Moderate"},{student:"Alex",subject:"maths",marks:"85",answer:"Moderate"},{student:"Alex",subject:"maths",marks:"85",answer:"Moderate"},{student:"Alex",subject:"science",marks:"82",answer:"Severe"},{student:"Alex",subject:"science",marks:"82",answer:"Severe"},{student:"Alex",subject:"science",marks:"82",answer:"Severe"},{student:"Alex",subject:"computer",marks:"90",answer:"Extreme"},{student:"Alex",subject:"computer",marks:"90",answer:"Extreme"},{student:"Alex",subject:"computer",marks:"90",answer:"Extreme"},{student:"john",subject:"maths",marks:"90",answer:"Extreme"},{student:"john",subject:"maths",marks:"90",answer:"Extreme"},{student:"john",subject:"maths",marks:"90",answer:"Extreme"},{student:"john",subject:"science",marks:"85",answer:"Moderate"},{student:"john",subject:"science",marks:"85",answer:"Moderate"},{student:"john",subject:"science",marks:"85",answer:"Moderate"},{student:"john",subject:"computer",marks:"87",answer:"Extreme"},{student:"john",subject:"computer",marks:"87",answer:"Extreme"},{student:"john",subject:"computer",marks:"87",answer:"Extreme"}];

//find all unique inputs, i.e. entry with unique strudent and subject
var uniqueInput = [...input].reduce((unique, obj) => {
  if (unique.filter(({student,subject}) => student === obj.student && subject === obj.subject /* && otherKeyFeatureUsedForUniqueness */).length === 0) return [...unique, obj]; //if not already inserted
    return unique; //already inserted
}, [])

var finalArray = [...uniqueInput].reduce((alreadyInsertedStudent, currentStudent) => {
    //get array of students without current student
    var arrWithoutObj = alreadyInsertedStudent.filter(({student}) => student !== currentStudent.student /* && the student or class or other properties which is constant across the duplicated rows in original input array, you can add here*/); 
    
    //if the student is not present, then withoutArray === currentarray
    //if yes, then insert the student and subject 
  if (arrWithoutObj.length === alreadyInsertedStudent.length) return [...alreadyInsertedStudent, {student: currentStudent.student, [currentStudent.subject]: currentStudent.marks, answer: currentStudent.answer/*, ...rest additional unique row defining Properties of final answer, you can add here*/}];
    //if student already inserted, then add the subject marks to that student 
    return [...alreadyInsertedStudent].map((prev) => prev.student === currentStudent.student ? {...prev, [currentStudent.subject]:currentStudent.marks} : prev);
}, [])

console.log(finalArray)


Related Query

More Query from same tag