So here's what I'm trying to do, I have an application I've been working on that allows users to read articles and take quizzes on them, each article is contained in a category. Category has an _id which is unique. Quiz attempts are held within another table which refrences the article, which refrences the category.
I have looped through all of the quiz attempts and store their keys and values in an array of objects which looks like the following:
const userScoreArray = [];
for(let i = 0; i < data[1].length; i ) {
userScoreArray.push({[data[1][i]['dataValues']['article_id']]: data[1][i]['dataValues']['score'] }) // overall
}
Now I have an array which stores quiz attempts for each category:
[
{4: 5},
{4: 1},
{3: 6},
{5: 0}
// { category: score }
]
How would I be able to get into this array, select all objects with the key of "4" and and then add all of their values together, and then again grab all objects with the key of "5" and add their values together? I was thinking of using a loop to do it but my brain starts to steam right then.
CodePudding user response:
You can use an Array.reduce iterator, then Object.keys() and Object.values() to extract the numbers for comparing and adding
let data = [
{4: 5},
{4: 1},
{3: 6},
{5: 0}
// { category: score }
];
const getScoreFor = n => {
return data.reduce((b, a) => {
return b (Object.keys(a)[0] == n ? Object.values(a)[0] : 0);
}, 0);
}
console.log(getScoreFor(4))
CodePudding user response:
You can use the reduce method as follows:
const array = [{ 4: 5 }, { 4: 1 }, { 3: 6 }, { 5: 0 }];
const accArray = array.reduce((acc, obj) => {
if (obj[4] ?? obj[5]) {
acc = Object.values(obj)[0];
}
return acc;
}, 0);
console.log(accArray); // 6
MDN ref.:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
By using reduce(), you loop through the array having access at each iteration to an accumulator, the current element and the current index. The initial value of the accumulator, on the above example, is set to zero; at each iteration, we check if the object has a key equal to 4 or 5; if the condition is true we add to the accumulator the value of that object, then it is returned the accumulator (because that is how the reduce method works).
OBS: I used the nullish coalescing operator (??) just in case you need to use 0 as key ({0: any_value}), as the or operator (||) works with falsy values.