Calculate the total value of a certain field within an array when a specific condition is satisfied

I have two sets of data. I am looking to calculate the total time_spent for each course_id that appears in both set 1 and set 2.

let set1 = [
  { instructor_id: 7, course_id: 19, lesson_id: 1, time_spent: 0 },
  { instructor_id: 7, course_id: 19, lesson_id: 2, time_spent: 0 },
  { instructor_id: 7, course_id: 19, lesson_id: 3, time_spent: 0 },
  { instructor_id: 7, course_id: 20, lesson_id: 4, time_spent: 80 },
  { instructor_id: 7, course_id: 20, lesson_id: 5, time_spent: 40 },
  { instructor_id: 8, course_id: 21, lesson_id: 6, time_spent: 0 },
];

let set2 = [
  { id: 19, title: "Course 19", duration: 180 },
  { id: 20, title: "Course 20", duration: 120 },
];

// expected output
newSet = [
  { instructor_id: 7, course_id: 19, time_spent: 0 },
  { instructor_id: 7, course_id: 20, time_spent: 120 },
];

Answer №1

There are numerous methods to achieve this task, and even though the specific actions for all the fields were not clearly defined, utilizing Array.reduce can efficiently carry out a selective sum.

One smart approach is to multiply a value by a boolean in order to sum only the matching values, while adding 0 for non-matching items. The expression condition * value is essentially equivalent to the ternary operation condition ? value : 0

const arr1 = [
  { instructor_id: 7, course_id: 19, lesson_id: 1, time_spent: 0 },
  { instructor_id: 7, course_id: 19, lesson_id: 2, time_spent: 0 },
  { instructor_id: 7, course_id: 19, lesson_id: 3, time_spent: 0 },
  { instructor_id: 7, course_id: 20, lesson_id: 4, time_spent: 80 },
  { instructor_id: 7, course_id: 20, lesson_id: 5, time_spent: 40 },
  { instructor_id: 8, course_id: 21, lesson_id: 6, time_spent: 0 },
];

const arr2 = [
  { id: 19, title: "Course 19", duration: 180 },
  { id: 20, title: "Course 20", duration: 120 },
];

const result = arr2.map(({ id }) => ({
  course_id: id,
  time_spent: arr1.reduce(
    (prev, cur, index) => prev + (cur.course_id == id) * cur.time_spent
    , 0)
}));

console.log(result);

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

Aggregate the JSON data by grouping and calculating the total value

Looking to organize a set of JSON values by grouping them based on different geographical regions. Identified,Proposal Submitted,QO under Evaluation,Negotiation & Contracting,Closed Lost,Closed Won are all grouped according to count and pipelinevalue ...

Automating Python functions with Selenium API after exceeding page load time

I am currently working on a Python script that uses Selenium with the Chrome webdriver. Occasionally, the script gets stuck while loading pages because of JavaScript trying to load in the background. I have tried using the line: driver.execute_script("$(w ...

Utilizing a JSON file for long-term storage of a compact database in JavaScript

As a newcomer to JSON, I wanted my webpage to display a small database of records in a table without using a traditional database like MySQL. Instead, I decided to read data from and write it out to a JSON file for convenient and persistent storage on my w ...

Initiate a project and organize by using mongoose to sort array fields

My mongoose model for a post on a social networking platform is called PostModel: { caption: String, likes: [] // array to store information about users who liked the video, essentially referencing another model comments: [] // array to hold comment object ...

The statement ""x=x || 4" will result in a `ReferenceError: x is not defined` because the

What is the reason behind receiving a ReferenceError: x is not defined error when using x = x || 4 or even x=(x||5), while var x = x || 4 operates as intended? ...

I want to retrieve a string of data from a JSON response in Php instead of an array

Setting up a personal page to track my dogecoin online transactions has been quite a task. Fortunately, the RPC server/client connection is up and running smoothly. The listtransactions method neatly organizes my transaction history as an array, which I t ...

Exploring the possibilities of using AngularJS for AJAX functionality in a Ruby On Rails

I recently started learning AngularJS and Rails, and I attempted to develop a Rails application incorporating AngularJS. Currently, I am looking to make a POST request to send data and insert it into the database. In the Activity Controller: def create ...

Exploring the world of variable scopes in Node.js

I'm new to exploring the world of node.js, particularly trying to grasp the concept of asynchronous processing loops. Let's say I have an array called var counter = []; declared at the beginning of my server.js script. Next, I have a POST handl ...

The functionality of jQuery touch events on iOS devices is not functioning properly

I'm encountering issues with jQuery touch events on iOS devices. Here is my current script: $(document).ready(function(){ var iX = 0,iY = 0,fX = 0,fY = 0; document.addEventListener('touchstart', function(e) { ...

Enhancing wordpress custom fields using ajax without overwriting them

Seeking assistance with updating a custom field in WordPress. I have a gallery of images with textareas for comments attached to each image. Currently, I can enter text into a textarea and save it instantly using AJAX to the database. However, when I add a ...

Does the current protected route that I am on restrict the user from navigating back to the Home component?

I'm having trouble figuring out how to redirect the user to the Home component when they logout. The API is functioning correctly based on my tests. However, I am unsure of how to implement the logout method in the current context to successfully log ...

What rules should be followed in Python when it comes to using nested parentheses in functions?

Currently in the process of deleting my account from this platform, I am intentionally adding unnecessary content to this post. Please refrain from restoring the previous content. - Original Poster ...

The JQuery JavaScript function fails to complete its execution

Question: How can I resolve the issue where my PHP file returns a large JSON string with approximately 2000 elements, each having 14 child elements? When using jQuery AJAX to fetch the JSON and populate an ID-identified table, the filling process stops mid ...

Exploring various data promises in AngularUI router

I am attempting to utilize the $q service to resolve multiple promises using the $q.all() function with AngularUI router. However, I am encountering issues where it is failing or not functioning as expected. This snippet is from my configuration file that ...

How to customize the radio button style in Angular 11 by changing the text color

Hey guys, I'm working with these radio buttons and have a few questions: <form [formGroup]="myForm" class="location_filter"> <label style="font-weight: 500; color: #C0C0C0">Select a button: </label& ...

Assign the value from JavaScript to the element with the "ng required" attribute, without resetting frm.$error.required to false

My situation involves using a button with ng-style that relies on frm.mybtn.$error.required as follows: ng-style="frm.mybtn.$error.required?{'border-color':'#a94442'}:''" I am updating the value of the button from JavaScript ...

The AngularJS ng-if directive functions on a variable will only function on the

I'm currently working on updating an old codebase that was written in AngularJS, a framework I am not very familiar with. My task is to implement a spinner that appears when an HTTP request is sent and disappears once the response is received. The sp ...

Cease the progress of a Sequelize promise within an Express.js application

Exploring the realm of promises is a new adventure for me, and I'm still trying to grasp their full potential in certain situations. It's refreshing to see Sequelize now supporting promises, as it greatly enhances the readability of my code. One ...

gRaphael - the struggle of animating a line chart

Encountering an issue with the gRaphael javascript line chart library. Creating a line chart from a CSV file with five columns (# of minutes, time, waiting time, in treatment, closed, in location). Previously drew full chart without animation successfull ...

A different approach for managing lengthy API processes in Node without using the traditional "Notification URL"

Developing an API that involves a lengthy data conversion process lasting up to 60 seconds presents the challenge of keeping users informed about any potential errors and the progress of the conversion stage. While sending WebSocket events is feasible for ...