首页 > 解决方案 > How to get the sum of values per day grouped by day from an array in JS?

问题描述

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 },    
    ]

标签: javascriptarraysdategroupingmilliseconds

解决方案


首先,您需要将date(我相信以毫秒为单位)转换为日期并使用getDay(). 创建一个天数组,遍历天数,如果转换后的日期与天数相同,则将值相加。看看下面的片段。

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


推荐阅读