Skip to content
Advertisement

How to select all objects within an array by their key and add their values together?

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.

Advertisement

Answer

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))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement