What is the best way to choose all elements from an array based on their key and then combine their values?

Currently, I am working on an application that allows users to read articles and take quizzes. Each article is assigned to a unique category with its own _id. Quiz attempts are stored in a separate table that references the articles, which in turn reference the categories.

To analyze quiz attempts, I have created an array of objects by looping through the data:

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
   }

This array now contains quiz attempts per category like this:

[
{4: 5},
{4: 1},
{3: 6},
{5: 0}
// {category: score}
]

The challenge now is to extract objects with key "4" from the array, add their values together, and repeat the process for objects with key "5". While a loop might work, it's a bit overwhelming. Any suggestions on a more efficient approach?

Answer №1

To efficiently extract and compare numbers for addition, you can utilize the Array.reduce iterator along with Object.keys() and Object.values().

let dataset = [
{4: 5},
{4: 1},
{3: 6},
{5: 0}
// { key: value }
];

const calculateTotalFor = num => {
  return dataset.reduce((sum, obj) => {
    return sum + (Object.keys(obj)[0] == num ? Object.values(obj)[0] : 0);
  }, 0);
}

console.log(calculateTotalFor(4))

Answer №2

Here is an example of how you can utilize the reduce method:

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

If you want more information on the reduce() method, you can refer to this MDN link:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

When using reduce(), each iteration provides access to an accumulator, current element, and current index. In the example above, the initial accumulator value is set to zero. During each iteration, we check if the object contains a key equal to 4 or 5, and if true, we add the object's value to the accumulator before returning it (as per the reduce method behavior).

Note: The nullish coalescing operator (??) was used as a precaution in case you need to use 0 as a key ({0: any_value}), as the logical OR operator (||) works with falsy values.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing me to have to click the button twice in order to view my dropdown list? Any suggestions on how to

I am facing an issue where I have to click twice on the "Action" button in order to see my dropdown list. How can I resolve this? Is there a way to fix it? $(document).ready(function() { $(".actionButton").click(function() { $dropdown = $("#cont ...

What is the process for including a JavaScript file in an HTML document?

Greetings to all and thank you for taking the time! I have a straightforward query for you.. I have designed an html page featuring only a basemap (open street map). Moreover, I possess a javascript file which utilizes your coordinates to calculate a perce ...

Can you show me how to condense this using the ternary operator?

Although I don't necessarily have to refactor this code, I am intrigued by the idea of doing so. handleError: ({ error, email, password }, props) => authError => { if (email === "" || password === "") { return { error: `Plea ...

Delete items within the first 10 minutes of shutting it down

Is there a way to temporarily remove a newsletter element for 10 minutes after closing it on a webpage? The idea is that once the panel is closed, it should stay hidden even if the page is refreshed within that timeframe. I was considering using local stor ...

Snatching the lesson found within an iframe

Is it possible to obtain the id from an iframe using the following method? var iFrame = window.top.document.getElementById('window_<?php echo $_product->getId() ?>_content'); However, I am struggling to understand how to retrieve the c ...

Using Spring MVC and Thymeleaf to dynamically load new HTML pages on ajax calls

Hello there, I'm looking to dive into using thymeleaf for my web application. My goal is to create a simple website with HTML pages. Below is the URL of my landing page controller that returns the index.html page: @RequestMapping("/index") public Str ...

Retrieving an attribute through the act of clicking a button

How can I retrieve the rel attribute value when clicking on a button with the class selector? <button class="nameClass" rel="relName">Content</button> I am attempting to achieve this by: $(".nameClass").click(function(){ // Here is where ...

Which framework should be used: client-side or server-side?

I am working on a project similar to craiglist, where users can post announcements for everyday items like cars and flats. I have already developed a significant portion of the backend using a RESTful API in three-tier architecture with Java, connecting to ...

jQuery click event not working post Ajax request returned a 403 error

I am facing an issue with my ajax request where I receive a 403 error message. Strangely, when this error occurs, the click() function associated with the ajax call stops working. There is no manipulation of HTML elements before or after the ajax call, and ...

Substitute the string (3-11-2012) with a different date layout (3 november 2012)

Can anyone guide me on how to convert text strings like '11-1-2012' into date strings like '11 januari 2012'? I've been looking for a solution, but haven't found exactly what I need. The month names should be in Dutch. I attem ...

Unexpected Issues with Page Refresh in AngularJS

I am currently working on an Angular application using the MEAN stack. Here's a scenario: imagine you have an express route that queries the database and sends the results back in the response: app.get('/api', function(req, res){ Todo.f ...

Loop through an array of div IDs and update their CSS styles individually

How can I iterate through an array of Div IDs and change their CSS (background color) one after the other instead of all at once? I have tried looping through the array, but the CSS is applied simultaneously to all the divs. Any tips on how to delay the ...

Nextjs introduces an innovative "OnThisDay" functionality, leveraging getServerSideProps and Date.now() to provide real-time information

I am currently working on adding an "OnThisDay" feature in my Nextjs project, inspired by Wikipedia's style of displaying events that happened on a specific date. To achieve this, I have implemented a function structured like the following code snippe ...

React Router malfunctioning on production environment when integrated with an Express backend

My Single Page application is built using React for the frontend and Express for the backend. Within the application, there are two main components: and . The goal is to display the component when the "/"" URL is requested, and show the component for an ...

Troubleshooting Problem with MVC Ajax Requests

When working with an MVC view, I have a submit button that includes validation checks. If the validation fails, I return false to prevent the form from being submitted. In addition to standard validation, I also use an Ajax GET request to check for duplic ...

Tips for utilizing the onload function in jquery

Having an issue where I have a button that I want to set time, and in order for the function to run correctly, it needs to be defined on the body element. This works fine with plain JavaScript, but I am encountering an error when trying to use jQuery. < ...

Tips for obtaining the output of an asynchronous function that contains a query within a loop

I am facing an issue where I need to retrieve a value after the completion of a for loop that is nested within an asynchronous function. The loop contains a query that inserts data into a database. The function seems to be functioning correctly, but when ...

The content of a Puppeteer page mysteriously disappears when transferred to another function

My current project involves using Puppeteer for web scraping on my website. I encountered a strange issue where the await page.content() works fine when I console log the content, but turns out to be null when passed as an argument to another JavaScript ...

Ways to retrieve JSON string from responsetext in JavaScript

After spending the entire day on this, I still can't figure it out. I have AJAX that fetches a JSON string from a PHP script, but now I need to work with it in JavaScript. Here's what I've tried: var xmlhttp; xmlhttp=new XMLHttpRequest(); ...

Is it possible to include three sorting states in jQuery DataTables: ASC, DESC, and NO_SORT?

When clicking on a column header in jQuery DataTables, the sorting order toggles between ascending (Down Arrow) and descending (Up Arrow). However, I am looking to customize this behavior: 1st-click ascending 2nd-click descending 3rd-click no-sorting 4th- ...