In Python, it is easy, but in JavaScript, it is giving me such a headache.
I am using Chart.js, D3 and Date-FNS. I am using CSV. You can check my CSV file here.
I would like to get the difference of cases or deaths between each day, so theoretically I could get the number of new cases or deaths per day instead of total cases. I mean to resample every 2 days using a arithmetic operator. It's just subtracting that is giving me such a headache.
Similar to Python's Pandas' diff()
in the questions:
- Is there a function to get the difference between two values on a pandas dataframe timeseries?,
- Calculating difference between two rows in Python / Pandas
- How to calculate day's difference between successive pandas dataframe rows with condition.
I was suggested to use map()
and reduce()
, but nothing worked.
Inspired by Subtract values in column in JS, I tried:
const DailyDeathsData = dates.map((d, pair) =>
{
var firstVal = parseInt(d.totalDeaths[pair]);
var secondVal = parseInt(d.totalDeaths[pair + 1]);
var daily = (firstVal > secondVal) ? firstVal - secondVal : secondVal - firstVal;
return daily;
});
But it returned all zeros.
Then, inspired by JavaScript go through array and subtract each item with next, using slice
, map
and reduce
:
const DailyDeathsData = dates.slice(1).map((v, i) => v.totalDeaths - dates[i].totalDeaths);
It also returned all zeros.
Then, using reduce
:
const DailyDeathsData = dates.reduce((v1, v2) => { return v1.totalDeaths - v2.totalDeaths });
But it did not display.