Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Substract value with previus value

I am making app in vue.js and right now I have a little problem

async fetchCovidDataByDay(){
    const res = await fetch(`https://api.covid19api.com/live/country/${this.name}/status/confirmed`);
    const data = await res.json();
    this.arrConfirmed= [];
    this.arrDeaths = [];
    this.arrRecovered = [];
    this.arrActive = [];

    data.forEach(item =>{
      const date = moment(item.Date).format('MMMM Do YYYY');
      const {
        Confirmed,
        Deaths,
        Recovered,
        Active
      } = item;
      this.arrConfirmed.push({date, total: Confirmed})
      this.arrDeaths.push({date, total: Deaths})
      this.arrRecovered.push({date, total: Recovered})
      this.arrActive.push({date, total: Active})
    })
    return data;
  },

so my total should be Confirmed[i] – Confirmed[i-1] 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you change the forEach to

data.forEach((item, i) =>{

You can access the previous item like so

  this.arrConfirmed.push({date, total: Confirmed - (data[i - 1]?.Confirmed || 0)})

?.Confirmed || 0 is purely for index 0, when there is no previous item

const data = [{Confirmed: 100}, {Confirmed: 120}, {Confirmed: 180}, {Confirmed: 300}];
const arrConfirmed= [];
let prevConfirmed = 0;
data.forEach((item, i) =>{
    const { Confirmed, } = item;
    arrConfirmed.push({total: Confirmed - (data[i - 1]?.Confirmed || 0)});
});
console.log(arrConfirmed);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading