0

I want to merge every student that did the same subject together into an array and I want to return the entire result as an array. Please check the output I comment below for a better understanding

let utme = [
     {subject:'English',    student:'Doe'},
     {subject:'Math',       student:'wale'},
     {subject:'Chemistry',  student:'Bisi'},
     {subject:'Math',       student:'bola'},
     {subject:'Biology',    student:'Raji'},
     {subject:'Chemistry',  student:'John'},
     {subject:'Physics',    student:'Bolu'},
     {subject:'Math',       student:'John'},
]

function merge(arr){
    const hash = {};
   return arr.reduce((accu, curr) => {
      
      hash['subject'] = curr.subject;
      hash['student'] = [].concat(curr.student);
      console.log(hash)
      

   },[])
}

merge(utme)


/*     this is the result I want
   [
     {subject:'English',    student:['Doe']},
     {subject:'Math',       student:['Wale', 'Bola', 'John']},
     {subject:'Chemistry',  student:['Bisi','John']},
     {subject:'Biology',    student:'Raji'},
     {subject:'Physics',    student:['Bolu']}      
]
*/
Wasiu
  • 239
  • 2
  • 11

0 Answers0