-3

In JS, given an array of objects, like:

    [{
      date: 1525655429184,
      value: 20.00
    },{
      date: 1525655429184,
      value: 3.99
    },{
      date: 1526001029184,
      value: 19.00
    },{
      date: 1526001025184,
      value: 4.30
    }]

Where the 'date' property is a date in milliseconds, and the 'value' property is a monetary represented by a float, and each object of this array can be one day of the month with his associated value.

I want to get the sum of value for each week day, to show in a chart of total values x day.

So the output should be like this example:

    [
      { day: 'Sun', sum: 23.99 },
      { day: 'Mon', sum: 0 },
      { day: 'Tue', sum: 22.2 },    
      { day: 'Wed', sum: 22.3 },    
      { day: 'Thu', sum: 2.2 },    
      { day: 'Fri', sum: 32.2 },    
      { day: 'Sat', sum: 22.43 },    
    ]
Josiel Faleiros
  • 1,437
  • 2
  • 15
  • 19

2 Answers2

2

First, you need to convert the date (which i believe in milliseconds) into date and get the day by using getDay(). Create an array of days, loop thru the days, and if the converted date is the same as the day sum the values. Take a look at the snippet below.

var data = [{
  date: 1525655429184,
  value: 20.00
}, {
  date: 1525655429184,
  value: 3.99
}, {
  date: 1526001029184,
  value: 19.00
}, {
  date: 1526001025184,
  value: 4.30
}]
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var sumVals = [];
var daysSum = [];

var sumVal = days.forEach(function(day) {
  var total = 0;
  data.forEach(function(items) {
    var d = new Date(items.date);
    var formattedD = days[d.getDay()];
    if (day === formattedD) {
      total += parseFloat(items.value);
    }
  })
  sumVals.push(total)
 daysSum.push([day, total])
})
console.log(days)
console.log(sumVals)
console.log(daysSum)//just to show if it matches
Sachi Tekina
  • 1,800
  • 5
  • 28
  • 50
  • 1
    But the day may be different depending on the timezone, e.g. 1525910400000 is 2018-05-10T00:00:00.000Z, which is a Thursday, but in New York (UTC -4) it's still Wednesday. – RobG May 10 '18 at 11:59
  • this answer solves partially, because there can be data with tens or hundreds of days, and this answer will not solve that. – Josiel Faleiros May 10 '18 at 13:26
  • @JosielFaleiros It will actually sum all the values with the same day. – Sachi Tekina May 10 '18 at 13:33
  • @SachiTekina yes, it does sum all the values grouped by day, but the data can have tens or hundreds of days, and the answer not work for that, and that's my case, sorry if I didn't explain clear – Josiel Faleiros May 10 '18 at 13:44
0

Milliseconds in a day:

var millsperday = 1000*60*60*24;

Current millisecond/day offset:

var d = new Date();
var m = d.getTime(); 
d.setHours(0,0,0,0);
var o = d.getTime()-m;

So, to divide a list of (unixtime) milliseconds:

for (i=0;i<list.length;i++) {
  numberofday = Math.floor((list[i]-o)/millsperday) ;
}
Sanxofon
  • 759
  • 9
  • 20