Determine the Ratio by comparing shared keys within an array of dictionaries

Looking to create a function that can calculate ratios based on specific keys and control which keys are eligible for ratio calculation.

num = [{"HCOName":8919,"timestamp":"2019-01-01T00:00:00.000Z","Territory":"USA"},
       {"HCOName":8275,"timestamp":"2019-02-01T00:00:00.000Z","Territory":"USA"}, 
       {"HCOName":8107,"timestamp":"2019-03-01T00:00:00.000Z","Territory":"USA"}, 
       {"HCOName":8255,"timestamp":"2019-04-01T00:00:00.000Z","Territory":"BRAZIL"}, 
       {"HCOName":8802,"timestamp":"2019-05-01T00:00:00.000Z","Territory":"BRAZIL"}];
den = [{"HCP":9,"timestamp":"2019-01-01T00:00:00.000Z","Territory":"USA"},
       {"HCP":5,"timestamp":"2019-02-01T00:00:00.000Z","Territory":"USA"},
       {"HCP":7,"timestamp":"2019-03-01T00:00:00.000Z","Territory":"USA"},
       {"HCP":2,"timestamp":"2019-05-01T00:00:00.000Z","Territory":"CANADA"}];

commonDimesion= ["timestamp", "Territory"]
function ratio(num,den,commonDimesion){
   <some code>
} 

anticipated outcome:

    [{"ratioResult":991,"timestamp":"2019-01-01T00:00:00.000Z","Territory":"USA"},
    {"ratioResult":1655,"timestamp":"2019-02-01T00:00:00.000Z","Territory":"USA"}, 
    {"ratioResult":1158.14,"timestamp":"2019-03-01T00:00:00.000Z","Territory":"USA"}]

Answer №1

If you're looking to streamline your process, consider utilizing the reduce function in the following manner:

var num = [{"HCOName":8919,"timestamp":"2019-01-01T00:00:00.000Z","Territory":"USA"}, {"HCOName":8275,"timestamp":"2019-02-01T00:00:00.000Z","Territory":"USA"}, {"HCOName":8107,"timestamp":"2019-03-01T00:00:00.000Z","Territory":"USA"}, {"HCOName":8255,"timestamp":"2019-04-01T00:00:00.000Z","Territory":"BRAZIL"}, {"HCOName":8802,"timestamp":"2019-05-01T00:00:00.000Z","Territory":"BRAZIL"}];
var den = [{"HCP":9,"timestamp":"2019-01-01T00:00:00.000Z","Territory":"USA"}, {"HCP":5,"timestamp":"2019-02-01T00:00:00.000Z","Territory":"USA"}, {"HCP":7,"timestamp":"2019-03-01T00:00:00.000Z","Territory":"USA"}, {"HCP":2,"timestamp":"2019-05-01T00:00:00.000Z","Territory":"CANADA"}];
var commonDimesion= ["timestamp", "Territory"];

var result = num.reduce((acc, {HCOName, ...rest})=>{
  denValue = den.filter(val=>commonDimesion.every(k=>val[k]==rest[k]))[0];
  if(denValue) acc.push({rationResult:HCOName/ denValue.HCP, ...rest});
  return acc;
},[]);

console.log(result);

Try incorporating this code snippet into your existing function and output the result. Hopefully, this solution proves beneficial for your needs. Much appreciated!

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

In order to set a condition for the mat date picker to display a text box in Angular if the selected date is for someone under 18 years old

I need assistance with displaying a text field based on age validation. The requirement is to show the input field only if the age is less than 18. Below is the code snippet I am currently working with: <form [formGroup]="form"> ...

"Optimizing Performance: Discovering Effective Data Caching

As a developer, I have created two functions - one called Get to fetch data by id from the database and cache it, and another called POST to update data in the database. However, I am facing an issue where I need to cache after both the get and update oper ...

Attempting to reduce the width of the dig when it reaches 400

I have a square element with a click event that increases its size by 50 pixels on each click. However, once it reaches a size of 400 pixels, the size decreases by 50 pixels with every click instead. Additionally, when the size of the square reaches 100 p ...

Building a bridge between React Native and MongoLab

I am currently in the process of developing a React Native application for iOS that will require querying a database. After some research, I have chosen to use MongoLab. Upon reviewing MongoLab's documentation, it is suggested to utilize the MongoDB D ...

How can I change the nested Material UI component style from its parent component?

I am currently incorporating a component from an external library into my project. However, I am facing limitations in customizing its style, especially when it comes to a button that is using material ui styles. Upon inspecting the element, I can see that ...

Error message: Unauthorized request error with the change.org JavaScript API

I am currently working on integrating the javascript API from change.org in order to retrieve all of my signed petitions for display on my source forge page. However, I am encountering an unauthorized request response from the change.org API. Despite tryi ...

Seeking assistance with using JavaScript to filter posts from Contentful for a Next.js website

Currently, I am integrating a Next.js blog with Contentful and employing queries to display posts on the homepage. While I can easily use .filter() to feature certain posts based on a boolean value, I am struggling to figure out how to fetch posts that mat ...

How can we access parameters in ag-Grid's Angular 1 onFilterModified event?

Currently, I am incorporating grid options using the code snippet provided below: var gridOptions = { columnDefs: columnDefs, rowData: null, enableFilter: true, onFilterChanged: function() {console.log('onFilterChanged');}, onFilterModified: fun ...

What is the process for verifying user authentication in a GET request?

My frontend utilizes Reactjs, while the backend is built with Nodejs and expressjs, connected to a Postgresql database. I have a basic signin page that authenticates users from the database. In my Reactjs application, once signed in, users can upload files ...

Understanding the functionality of a notification system

Planning to create an admin tasking system utilizing PHP, MySQL, and JavaScript. Curious about how the notification system operates and how it stores real-time data. Are there any good examples of a notification system? ...

Is there a way to dynamically insert page breaks in jspdf to ensure that tables do not split across multiple pages?

I am currently working on developing a website that can generate PDFs from database information, using PHP and MySQL to create tables with variable lengths. Sometimes, these tables may even span across multiple pages. If the first table takes up too much ...

Steps for creating a jQuery function that responds to changes in a text box value

Currently, I have a text box containing certain values and a submit button alongside a slider. When I click the submit button, the slider changes. However, I would like to achieve the functionality where instead of clicking the submit button, changing the ...

The method to permit a single special character to appear multiple times in a regular expression

I am currently working on developing a REGEX pattern that specifically allows alphanumeric characters along with one special character that can be repeated multiple times. The permitted special characters include ()-_,.$. For instance: abc_def is conside ...

Jquery code failing to trigger any response

Recently, I quickly created a jQuery script to dynamically populate a paragraph element in order to easily switch between player and server interaction options. However, I am currently facing an issue where my script does not populate as expected. I have a ...

Utilizing JQuery to extract data from a <select> dropdown menu

Is there a way to retrieve the current value of a SELECT tag using JavaScript or jQuery? I have tried using $('select').val(), but it only returns the default value and does not update when changed. Any suggestions on how to solve this issue? $( ...

What is the best way to make img-fluid function properly within Bootstrap Carousel?

I've been struggling to make my carousel images responsive by using the img-fluid tag, but I haven't had any success. I've attempted using !important and display: block, but nothing seems to work. I'm not sure what's causing the is ...

A method to transfer a floating point number from Python to JavaScript without using cgi

Running an Apache server from a Raspberry Pi, I have a Python script that prints sensor input to the console. A PHP script then processes this output and controls a light based on the sensor reading before printing it again. Everything works fine when exec ...

Getting values from a PHP multidimensional array that has been decoded from JSON can be achieved by accessing the different levels of the array using

I am currently integrating PayPal payments into my website. After the Paypal API sends me the order details in JSON format to my success.php script, I need to extract and store each variable in my database. To retrieve the JSON data, I use the following ...

Bring in a pair of documents

Just started learning about imports and encountered a particular issue. After installing the package in your gulpfile, you must include the following line: const sass = require('gulp-sass')(require('sass')); Is there a way to achieve ...

Create a notification box that appears after a successful axios request

One of the functions I have is to store an expense in my application. storeExpense(context, params){ axios.post('api/expenses', params) .then( response => { context.dispatch('getExpenses') }) .catch( error =&g ...