我希望编写一个JS函数,它以名称列表为参数,并能按指定的列名称进行分组和聚合。例如,我的数据可能如下所示:
const SALES = [
{ lead: 'Mgr 1', revenue: 49.99, repName: 'Rep 1', forecast: 81.00 },
{ lead: 'Mgr 1', revenue: 9.99, repName: 'Rep 1', forecast: 91.00 },
{ lead: 'Mgr 1', revenue: 9.99, repName: 'Rep 13', forecast: 82.00 },
{ lead: 'Mgr 2', revenue: 99.99, repName: 'Rep 3', forecast: 101.00 },
{ lead: 'Mgr 2', revenue: 9.99, repName: 'Rep 5', forecast: 89.00 },
{ lead: 'Mgr 3', revenue: 199.99, repName: 'Rep 6', forecast: 77.00 }
];
我可以按照以下方式对这些数据进行分组和聚合:
let grouped = {};
SALES.forEach(({lead, repName, revenue}) => {
grouped[[lead, repName]] = grouped[[lead, repName]] || { lead, repName, revenue: 0 };
grouped[[lead, repName]].revenue = +grouped[[lead, repName]].revenue + (+revenue);
});
grouped = Object.values(grouped);
console.warn('Look at this:\n', grouped);
然而,我希望它能更具动态性,这样我就不必为所有可能的分组和聚合组合编写if-else语句。以下代码显示了我想要使其工作的内容,但目前并没有实现。
function groupByTotal(arr, groupByCols, aggregateCols) {
let grouped = {};
arr.forEach(({ groupByCols, aggregateCols }) => {
grouped[groupByCols] = grouped[groupByCols] || { groupByCols, aggregateCols: 0 };
grouped[groupByCols].aggregateCols = +grouped[groupByCols].aggregateCols + (+aggregateCols);
});
grouped = Object.values(grouped);
return grouped;
}
groupByTotal(SALES,['lead','repName'],'revenue')
预期输出可能看起来像这样:
[
{ lead: "Mgr 1", repName: "Rep 1", revenue: 59.98 },
{ lead: "Mgr 1", repName: "Rep 13", revenue: 9.99 },
{ lead: "Mgr 2", repName: "Rep 3", revenue: 99.99 },
{ lead: "Mgr 2", repName: "Rep 5", revenue: 9.99 },
{ lead: "Mgr 3", repName: "Rep 6", revenue: 199.99 }
]
理想情况下,我希望能够传入任意数量的列名称进行分组或聚合。非常感谢您的帮助。
aggregateCols
属性的数组。计数会类似。在对象创建时添加默认的count = 1
。当更新时,count++
。 - adiga