javascript - 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 },
]
解决方案
首先,您需要将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
推荐阅读
- python - 通过对最后 4 层求和的 BERT 句子嵌入
- tensorflow - 从 tensorflow 2.0 中保存的模型运行预测
- python - 为什么我的代码中有回溯和索引错误?
- c# - 为什么我的 GridView 末尾有一个空行?
- python - Pandas:生成多个/条件聚合列的更好方法
- visual-studio - 使用 NuGet 进行全局包安装
- angular - Angular 需要加载带有前面斜杠的模块
- git - 我们如何将更改从新分支推送到 GitHub Wiki?
- java - java中关于选择排序的运行时错误
- c++ - 在 priority_queue 中使用默认容器但自定义比较器