An array of objects is generated from a mongoDB query representing users' quiz attempts and stored in a variable called res.locals.spellingTestResults
. Users can have multiple attempts at the quiz.
[{
_id: {
user: {
name: 'PageHill Class1 Child',
userType: 'Child',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22174340151b41411b13111a16124311171b4444161017441362474f52565b0c414d4f">[email protected]</a>',
__v: 0
}
},
data: [{
numberOfSpellings: 4,
wrongAnswers: ['of', 'spellings'],
rightAnswers: 2,
score: 2
},
{
numberOfSpellings: 4,
wrongAnswers: ['spellings'],
rightAnswers: 3,
score: 3
}
]
},
{
_id: {
user: {
name: 'PageHillAdmin',
userType: 'Teacher',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a20232421337979780a2d272b232664292527">[email protected]</a>',
__v: 0
}
},
data: [{
numberOfSpellings: 4,
wrongAnswers: ['first','spellings'],
rightAnswers: 0,
score: 3
},
{
numberOfSpellings: 4,
wrongAnswers: ['of', 'spellings'],
rightAnswers: 0,
score: 4
}
]
}
];
I aim to create an array of objects for each user, combining their wrongAnswers
arrays and then counting the instances of each item in the resulting array. The desired output should resemble the structure below:
[{
user: {
name: 'PageHill Class1 Child'
}
wrongAnswers: {
'spellings': 2,
'of': 1
},
user: {
name: 'PageHillAdmin'
},
wrongAnswers: {
'spellings': 2,
'first': 1,
'of': 1
}
}];
While I already have logic in place to combine all the wrong answers across all users, as shown below:
let allWrongAnswers = [];
res.locals.spellingTestResults.map(function(answers) {
answers.data.forEach(answer => {
allWrongAnswers = allWrongAnswers.concat(answer.wrongAnswers);
});
});
var countedSpellings = allWrongAnswers.reduce(function (allSpellings, spelling) {
if (spelling in allSpellings) {
allSpellings[spelling]++;
}
else {
allSpellings[spelling] = 1;
}
return allSpellings;
}, {});
My challenge lies in grouping and tallying the wrong answers for each individual user.