Search code examples
javascriptarraysreducedayjs

Why does summing up a variable from an array give me NaN? (Javascript)


I have this array containing appointments:

let appointments = [
{"appointmentId": 001239, "subject": "Something", "Client": "Bob", "StartTime": "2020-04-16T11:00:00.000Z", "EndTime": "2020-04-16T11:30:00.000Z", "km": 90},
{"appointmentId": 001240, "subject": "Something", "Client": "Alvera", "StartTime": "2020-04-16T11:00:00.000Z", "EndTime": "2020-04-16T11:30:00.000Z", "km": 50},
{"appointmentId": 001241, "subject": "Something", "Client": "Bob", "StartTime": "2020-04-17T11:00:00.000Z", "EndTime": "2020-04-17T11:30:00.000Z", "km": 30}]

Now what I want is to sum the km by client, so for example Bob: total: 120. Alvera total: 50. And also with the differences in minutes of StartTime and EndTime. With the use of dayjs library I calculate the difference between the times. This is a method which does the accumulation of km and Times. The km works perfectly, however, the difference gives NaN. What am I doing wrong?

  var result = [];

   this.appointments.reduce(function (res, value) {
if (!res[value.Client]) {
  res[value.Client] = {
    km: 0,
    Client: value.Client,
    StartTime: dayjs(value.StartTime),

    EndTime: dayjs(value.EndTime),
    difference: dayjs(value.EndTime).diff(dayjs(value.StartTime), 'minute')  % 60

  };
  result.push(res[value.Client])
}
res[value.Client].km += value.km;

res[value.Client].difference += value.difference; //here I try to sum the differences by Client, when I remove this line, I just see the difference of the first appointment.
return res;


 }, {});

Solution

  • Maybe this helps?

    let appointments = [
      {
        appointmentId: 001239,
        subject: "Something",
        Client: "Bob",
        StartTime: "2020-04-16T11:00:00.000Z",
        EndTime: "2020-04-16T11:30:00.000Z",
        km: 90
      },
      {
        appointmentId: 001240,
        subject: "Something",
        Client: "Alvera",
        StartTime: "2020-04-16T11:00:00.000Z",
        EndTime: "2020-04-16T11:30:00.000Z",
        km: 50
      },
      {
        appointmentId: 001241,
        subject: "Something",
        Client: "Bob",
        StartTime: "2020-04-17T11:00:00.000Z",
        EndTime: "2020-04-17T11:30:00.000Z",
        km: 30
      }
    ];
    
    let totals = appointments.reduce(function (res, value) {
      let diff = dayjs(value.EndTime).diff(dayjs(value.StartTime), "minute") % 60;
      if (!res[value.Client]) {
        // set initial value
        res[value.Client] = {
          km: value.km,
          Client: value.Client,
          difference: diff
        };
      } else {
        // sum up
        res[value.Client].km += value.km;
        res[value.Client].difference += diff;
      }
      return res;
    }, {});
    
    totals = Object.values(totals);
    
    console.log(totals);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.24/dayjs.min.js"></script>