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

What is the reason behind the execution of componentDidMount occurring after componentWillUnmount?

I have been exploring the differences between componentDidMount and componentWillUnmout by experimenting with the following code: class App extends React.Component { constructor(props) { super(props); this.state = { name: "", ...

Template7 produces a bizarre outcome referred to as "each this" whenever JSON is utilized

Currently, I am experimenting with dynamically loading content on Framework7/Template7 pages. Everything works perfectly fine when using static "context" in JSON format. However, when attempting to test it with real-world data from an API, I encounter a st ...

The value from the angular UI bootstrap datepicker is unavailable when using a JQuery expression

I have a question regarding the datepicker feature from the Angular UI bootstrap library. The documentation can be found here. After selecting a date using the datepicker, I am facing an issue with retrieving the text input using jQuery expressions. When ...

When a URL is triggered via a browser notification in Angular 2, the target component ceases to function properly

Whenever I access a URL by clicking on a browser notification, the functionality of the page seems to stop working. To demonstrate this issue, I have a small project available here: https://github.com/bdwbdv/quickstart Expected behavior: after starting t ...

Do elements containing {visibility:hidden} properties exist within the HTML DOM structure?

Do HTML elements that have the css property visibility:hidden still exist within the DOM tree? ...

Instructions on utilizing the CSSStyleSheet.insertRule() method for modifying a :root attribute

Is it possible to dynamically set the background color of the :root CSS property in an HTML file based on a hash present in the URL? The code provided does change the background color, but unfortunately, the hash value doesn't persist as users navigat ...

Ensure the validation of multiple form fields in a single function

I've implemented code to validate a form field as you input values, changing the border color to red if invalid or green if valid: function FormValidation(){ var fn=document.getElementById("firstName").value; if(fn == ""){ document.ge ...

Strip digits from XML element

Hello there, I am currently facing a challenge in extracting data from a python script that is directly linked to a server back-office written in php. To tackle this, I have converted the received array into JSON and then transformed it into XML within a p ...

Update settings when starting with chromedriver

I am currently using webdriver (), standalone selenium, and mocha for writing my test cases. These test cases are specifically designed for Chrome, so I rely on chromedriver for execution. However, when launching the browser, I need to ensure that the "to ...

A 'select all' checkbox in a PHP 'foreach loop' with JavaScript

I am in search of a solution to implement JavaScript in the given code block. My goal is to have the checkbox with id = alles automatically check all the checkboxes that are generated within the while loop. <form id="andere" name="andere" action="<? ...

The functionality of php.js is compromised

I've been attempting to integrate php.js into my scripts, but have encountered a problem. I debugged a function and loaded it onto a single page containing only jQuery and php.js, yet it is still not functioning properly. <script src="http://code. ...

Combining multiple keys into a single field during JSON Jackson deserialization

Trying to convert JSON into POJO has been a task I've been working on. My previous experience with Jackson involved converting standard JSON files, but now I'm faced with a scenario where I need to overwrite key values to a "default" class/variab ...

The div height adjustment peculiarities in IE7 and IE8 are causing quite a stir

I recently encountered a problem with my HTML/JS code that I thought was simple. The code is designed to expand the size of a div on mouseover and then collapse it back on mouseout. Here's how the code looks: CSS: .sign-in-up { position: absolut ...

Assign a variable the source of the web subsurface A-frame setting

I want to utilize the websurface A-frame component () to change the URL of the websurface when a button is clicked. I have defined a variable called source and I want the websurface URL to be updated to the value of this variable upon clicking the button. ...

Using percentages for sizing and margins in CSS

Looking to create a visually appealing page that always fills the entire screen? Check out this code snippet that does just that: #posts{ width:100%; height:auto; background:#666; } .entry{ float:left; margin-left: 4%; margin-top:10 ...

Loading JSON data from a file in an AngularJS service

Looking to retrieve JSON data from a file named driverStandings.json, which can be found in the structure from the provided image. I am utilizing a service API to fetch this information by using the code displayed below (refer to image). After compiling, ...

Developing a universally accessible variable for utilization in various functions

I'm having trouble understanding why 'currentPos.LatLng' is undefined when trying to access it outside the function even though it's part of an object. I want to be able to retrieve the current position values to use them in another fun ...

What is the best way to determine the position of a letter within a string? (Using Python, JavaScript, Ruby, PHP, etc...)

Although I am familiar with: alphabet = 'abcdefghijklmnopqrstuvwxyz' print alphabet[0] # outputs a print alphabet[25] #outputs z I am curious about the reverse, for instance: alphabet = 'abcdefghijklmnopqrstuvwxyz' 's' = al ...

A guide to extracting attribute values from HTML using Angular 4

I am currently working on an Angular 4 project where I needed to implement drag and drop functionality. To achieve this, I utilized the ng2-dragula plugin. Now, I have a new requirement which involves extracting the data-id attribute from each row after it ...

Is there a way to place my searchbox in the top right corner of the page?

I am currently working on creating a search function for my list of products. However, I have encountered an issue where the searchBox is not appearing in the top right corner as intended. Despite trying various solutions, I have been unsuccessful in movin ...