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] 🙂

>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);

Leave a Reply