I have an array of objects:
console.log(quizNight[0].round[--latestRound].t)
-> [ { teamID: 16867, correctAnswers: 1 },
{ teamID: 16867, correctAnswers: 1 },
{ teamID: 16867, correctAnswers: 1 } ]
and I want to have a correctTotalAnswers array to look like this:
[ { teamID: 16867, correctTotalAnswers: 3} ]
What would be the smartest way to go about it? The code which I have now:
let correctAnswersArrayRoung = quizNight[0].round[--latestRound].t;
let totalCorrentAnswersArray = [];
for (let correctAnswer in correctAnswersArrayRoung) {
console.log(correctAnswersArrayRoung[correctAnswer])
for(let element in totalCorrentAnswersArray){
if(element.teamID === correctAnswer.teamID){
element.totalCorrectAnswers = ++element.totalCorrectAnswers
} else {
totalCorrentAnswersArray.push({
teamID: correctAnswer.teamID,
totalCorrectAnswers: 1
})
}
}
}
console.log(totalCorrentAnswersArray)
this returns []
You can use reduce
this way (see the inline comments):
// Your initial data const initialArray = [ { teamID: 16867, correctAnswers: 1 }, { teamID: 16867, correctAnswers: 1 }, { teamID: 16866, correctAnswers: 1 } ] // Use reduce to loop through the data array, and sum up the correct answers for each teamID let result = initialArray.reduce((acc, c) => { // The `acc` is called "accumulator" and it is // your object passed as the second argument to `reduce` // We make sure the object holds a value which is // at least `0` for the current team id (if it exists, // it will be used, otherwise will be initialized to 0) acc[c.teamID] = acc[c.teamID] || 0 // Sum up the correctAnswers value acc[c.teamID] += c.correctAnswers return acc }, {}) // <- Start with an empty object // At this point the result looks like this: // { // "16866": 1, // "16867": 2 // } // Finally convert the result into an array result = Object.keys(result).map(c => ({ teamID: c, correctAnswers: result[c] })) console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.