javascript - 通过两个不同的键和总和值对数组进行分组
问题描述
我正在使用 React 上的数组,我正在尝试按月和年过滤它,我设法按月进行过滤,但由于某种原因我无法添加年键,这就是我到目前为止所拥有的:
这是我最初拥有的数组:
paid = [
{amount:155, month:11, year:2020, date:11-11-2020}
{amount:120, month:11, year:2021, date:05-11-2021}
{amount:135, month:12, year:2020, date:11-12-2020}
...
]
const group = groupBy(d, (invoices) => invoices.month); //d is the array called "paid"
这是 groupBy 函数:
function groupBy(list, keyGetter) {
const map = new Map();
list.forEach((item) => {
const key = keyGetter(item);
const collection = map.get(key);
if (!collection) {
map.set(key, [parseInt(item.amount)]);
} else {
collection.push(parseInt(item.amount));
}
});
return map;
}
这就是我得到的结果:
grouped = [
{name:11, values: [155,120...]},
{name:12, values: [135...]
];
我想要的是将它也按年份分组,例如,第 11 个月不应该有两个值,因为在原始数组上,我拥有的月份是 2020 年的 11 个月和 2021 年的一个,所以结果我想要的是:
grouped = [
{name:11/2020, values: [155...]},
{name:11/2021, values: [120...]},
{name:12/2020, values: [135...]
];
谁能帮我这个?
解决方案
如果我理解正确,您想对每年每月的所有值求和。我想这会奏效。
// Generate random data.
const genData = () => {
const d = [];
for(let i =0; i < 1000; i++) {
d.push({
year: Math.round(Math.random() * 10) + 2001,
month: Math.round(Math.random() * 12),
amount: Math.round(Math.random() * 100) + 100
})
}
return d;
};
// Sum all data per month per year
const sumData = (d) => {
const summed = {};
for(const {year,month,amount} of d) {
// By using a unique key for each year/month combi you can easily access the
// intermedeiate result and add another value.
const key = year + '/' + month;
// If it does not yet exist, create an empty record for this year/month
if(!(key in summed)) {
summed[key] = {year,month, sum:0, values:[]};
}
// Grab the intermediate values and add amount to sum and to values
summed[key].values.push(amount)
summed[key].sum += amount;
}
return Object.values(summed);
};
// Run all
const d = genData();
console.log(d);
console.log(sumData(d));
推荐阅读
- angular - 更改 ngForOf 以从 Behavior Subject 获取 Iterable
- java - org.apache.cxf.jaxrs.client.WebClient 中的 RecieveTimeout 和 SynchronousTimeout 有什么区别?
- node.js - 在 Node.js 中按顺序排列的“n”个 API 调用?
- asp.net - CurrentCulture 和 CurrentUICulture 是否已缓存?
- angular - 无法在离子 3 中获取未定义或空引用的属性“DestinationType”
- node.js - 如何在本地主机上访问磁盘上的图像并通过网站上的 url 访问
- c# - 如何验证具有在 Linq 表达式中传递的特定值的 Moq 方法调用
- javascript - 将 jsp 导航到 servlet 时出现 404
- php - 使用 ajax 请求发送 csrf_token
- spring-boot - Redis 缓存不适用于 atlassian-connect-spring-boot-jpa-starter