Imagine you were given the task to collate a log of student attendance. The log contains different courses that each student attended. Group every student that attended the same course together
[
{subject:'English', student:'Odunola'},
{subject:'Math', student:'Wale'},
{subject:'Chemistry', student:'Wasiu'},
{subject:'Math', student:'Bola'},
{subject:'Biology', student:'Segun'},
{subject:'Chemistry', student:'Ramoni'},
{subject:'Physics', student:'Bolu'},
{subject:'Math', student:'Bose'},
]
Output should look like this
[
{subject: 'English', student: ['Odunola']},
{subject: 'Math', student: ['Wale', 'Bola', 'Bose']},
{subject: 'Chemistry', student: ['Wasiu', 'Ramoni']},
{subject: 'Biology', student: ['Segun']},
{subject: 'Biology', student: ['Segun']},
{subject: 'Physics', student: ['Bolu']},
]
function collate(arr){
let store = {};
arr.forEach(one =>{
if(!store[one['course']]){
store[one['course']] = {course: one['course'], name: [].concat(one['name'])};
}else{
store[one['course']]['name'].push(one['name'])
}
})
return Object.values(store);
}
const chai = require("chai");
const assert = chai.assert;
chai.config.truncateThreshold=0;
describe("Collate Collections", () => {
it("Fixed tests", () => {
/* assert.strictEqual(collate([
{course:'English', name:'Odunola'},
{course:'Math', name:'Wale'},
{course:'Chemistry', name:'Wasiu'},
{course:'Math', name:'Bola'},
{course:'Biology', name:'Segun'},
{course:'Chemistry', name:'Ramoni'},
{course:'Physics', name:'Bolu'},
{course:'Math', name:'Bose'},
]), [ { course: 'English', name: [ 'Odunola' ] },
{ course: 'Math', name: [ 'Wale', 'Bola', 'Bose' ] },
{ course: 'Chemistry', name: [ 'Wasiu', 'Ramoni' ] },
{ course: 'Biology', name: [ 'Segun' ] },
{ course: 'Physics', name: [ 'Bolu' ] } ]); */
assert.strictEqual(collate([
{ course: 'St. Jude', name:'Jagaban'},
{ course: 'Red Cross', name:'Atiku'},
{ course: 'Americares', name:'Tinubu'},
{ course: 'St. Jude', name:'Gbeborun'},
{ course: 'Give Well', name:'Obasanjo'},
{ course: 'Red Cross', name:'Tinubu'},
{ course: 'Red Cross', name:'Obi'},
] ), [
{ course: 'St. Jude', name:['Jagaban', 'Gbeborun']},
{ course: 'Red Cross', name:['Atiku','Tinubu','Obi']},
{ course: 'Americares', name:['Tinubu']},
{ course: 'Give Well', name:['Obasanjo']},
] );
});
});