Calculate the number of days required for the value in an item to multiply by two

I'm currently working on a JavaScript project to create a table displaying the latest number of coronavirus cases. I've reached a point where I want to add a column showing how many days it took for the confirmedCases numbers to double. Here's an example:

{
  "message": "Success",
  "source": "JHU CSSE",
  "sourceURL": "https://github.com/CSSEGISandData/2019-nCoV",
  "updateDate": "2020-03-22T11:08:41.651Z",
  "data": {
    "3/15/20": {
      "Afghanistan": 16,
      "Albania": 42,
      
      ......
      // Truncated data for brevity

      "US": 3499,
      "Uganda": 0,
      "Ukraine": 3,
      "United Arab Emirates": 98,
      "United Kingdom": 1145,
      "Uruguay": 4,
      "Uzbekistan": 1,
      "Venezuela": 10,
      "Vietnam": 56,
      "Zambia": 0,
      "Zimbabwe": 0
    },
    
    ......
    // More data entries for each day
    
  }
}

Wouldn't it be interesting if we could obtain an object that shows the number of days it took for the cases in each country to double? That might provide valuable insights into the spread of the virus worldwide.

Answer №1

Track the initial count of infected individuals by country and then loop through the countries to determine if the count doubles the initial number.

// Keep track of days
let days = 0;

const countriesWithDoubleDayCount = {};
const dates = Object.keys(data.data);
const countries = Object.values(data.data);

// Initialize countries object with count set to zero
const groupByCountries = Object.keys(data.data["3/15/20"]).reduce((accu, name) => {
    accu[name] = 0;
    return accu;
}, {});

const initialCountCountryWise = {};

const doubleCount = countries.reduce((a, country, i) => {
    if (i < dates.length - 1) {
        // Calculate date difference
        days += Math.abs((new Date(dates[i + 1]) - new Date(dates[i])) / (1000 * 60 * 60 * 24), 10);
    }

    const countries = Object.entries(country);

    countries.forEach(([name, count]) => {
        // First Record 
        if (i == 0) {
            // Track initial count of infected people by country.
            initialCountCountryWise[name] = count !== 0 ? count : 1;
        }

        a[name] = count;
        const double = initialCountCountryWise[name] * 2;

        // Check if current count is greater than double the initial count
        // If it is, add to countriesWithDoubleDayCount Object.
        if (a[name] >= double && !countriesWithDoubleDayCount.hasOwnProperty(name)) {
            countriesWithDoubleDayCount[name] = days;
        }
    });

    return a;
}, groupByCountries);

console.log(countriesWithDoubleDayCount);

Note - Unfortunately unable to include a live Javascript code snippet due to character limitations.

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

using node and express to route and pass variables to a required module

In my primary index.js file, I have the following code: var express = require('express') require("dotenv").config(); const db = require('./services/db_service').db_connection() const customers = require('./routes/custo ...

An issue has occurred in AngularJS where the error message "ng areq not

I'm facing an issue with my meta controller, as I am trying to alter the meta tags dynamically. When checking the console, I encounter the error message error ng areq not a function. I have looked on StackOverflow for similar issues but couldn't ...

Trying to bring in components from directories above

I'm currently facing an issue with importing components from a parent directory into my project. My goal is to be able to use these components across multiple projects, which seems like the most straightforward approach. However, when I attempt this, ...

Colorful radial spinner bar

I am interested in replicating the effect seen in this video: My goal is to create a spinner with text in the center that changes color, and when the color bar reaches 100%, trigger a specific event. I believe using a plugin would make this task simpler, ...

When using HTML5's checkValidity method, it may return a valid result even if

Consider the following scenario: <input pattern="[a-z]"/> If you run the command below without entering any input: document.querySelector('input').checkValidity() You will notice that it actually returns true. This seems counterintuiti ...

Chrome reports a Javascript error: indicating that it is not recognizing the function

When working with a js file and html, I encountered an issue where one function works fine but another prompts an error in Chrome: Uncaught TypeError: specification_existing is not a function I'm puzzled as to why one function works while the othe ...

Challenges with Tab navigation in React and Ionic 5

I am facing a challenge with getting the tabs navigation to function correctly. Here is my current code: App.tsx: const App: React.FC = () => <IonApp> <IonReactRouter> <IonRouterOutlet id="main"> < ...

What is the best way to create a universal variable that can be accessed across all routes in an Express/

Exploring the world of nodejs and express, I have turned to the Parse API for my backend database needs. At the moment, I have an ajax post triggered on page load to one of my routers /getuser, which retrieves the current user if they are logged in. I am ...

I'm looking to transfer an integer to and from JSON using Java. Can anyone guide me on how to

I have been working on an API that processes HTTP requests and returns JSON reports. To test the functionality, I have experimented with both Java (using HTTPUrlConnection) and Python (using requests). The API itself is developed in Java Spark. I find Pyth ...

StealJS Module Repathing Techniques

There seems to be an issue with my setup, so I welcome all inquiries. I am utilizing an npm package called xrm-mock for a MS CRM mocking framework. Here is how I have configured it: steal.config({ meta: { "dependencyModule": { deps ...

Refresh PHP Calculator Display Once Results are Shown

Currently working on a basic calculator project coded in HTML, CSS, JS, and PHP. Here is a glimpse of it: The user input retrieval is handled by JS, while the actual calculations and result display are taken care of by PHP. I am striving to clear out the ...

Validation of forms in Angular using a pseudo submission method

On a webpage, there is a form with two buttons: one to calculate a price and the other to submit the form. Below is a basic example: <form novalidate name="formStep1"> <select ng-model="address" required> <option></option> ...

The Next.js website displays a favicon in Chrome, but it does not appear in Brave browser

As I work on my debut next.js website, I am configuring the favicon in index.js like this: <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> </Head> Initially, all my source ...

What is the best way to dynamically pass JSON object values to PHP?

Greetings, I am new to JSON and Ajax. Although my question may seem trivial, I believe that even the simplest inquiries are crucial in the learning process. My dilemma involves passing two parameters (giorno and periodo) via Ajax: For example: 'gior ...

Nock is capturing my request, however, my AJAX call is encountering an error

I am currently conducting a test on an AJAX request using the XMLHttpRequest method: export default function performTestRequest() { const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.com/service'); xhr.onload = ( ...

Adjusting the axis to maintain readability in vega-lite

In order to display a bar plot of measures where some values are significantly higher than others, I attempted to use a log scale and implement an outlier filtering step before plotting. I also wanted to try using an axis break to hide a large chunk of y ...

The glitch in VueJS's array updating functionality

I am facing an issue where I have an array called tiles with a title. On creating the instance, I add a field to this array named active. Subsequently, I display this array within an <li> element and iterate through it to display the title and activ ...

What is the method for accessing the value of variable "a" in the following code?

request(target, function (err, resp, body) { $ = cheerio.load(body); links = $('a'); $(links).each(function (i, link) { if ($(link).text().match('worker')) { var a = $(link).attr('href').toStri ...

Issue with Nuxt: Property accessed during rendering without being defined on the instance

As I attempt to create cards for my blog posts, I encountered an issue with a Post component in my code. The cards are displaying like shown in the picture, but without any text. How do I insert text into these cards? Currently, all the text is within attr ...

Interceptors in axios do not trigger when making requests through a PHP proxy

I am currently working on a React app that will be interacting with services hosted on a remote server. During development on my local machine using the react-scripts server at localhost:3000, I disable CORS in the browser and have no issues with axios f ...