You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中根据购买对象数组计算每位客户的平均消费金额?

如何在JavaScript中根据购买对象数组计算每位客户的平均消费金额?

嘿,我来帮你搞定这个计算每位客户平均消费的问题!咱们一步步来,先理清楚核心思路:首先得算出每个客户的总消费金额和购买次数,最后用总金额除以购买次数,就能得到每位客户的平均消费啦。

首先先确认一下你给的示例数据:

const purchases = [
  { customer: "Alice", amount: 250 },
  { customer: "Bob", amount: 400 },
  { customer: "Alice", amount: 150 },
  { customer: "David", amount: 300 },
  { customer: "Bob", amount: 200 },
  { customer: "Charlie", amount: 100 },
  { customer: "David", amount: 100 }
];

第一步:聚合客户的总消费和购买次数

咱们可以用Array.reduce()方法来遍历数组,把每个客户的消费数据聚合到一个对象里。这个方法特别适合做这种数组的聚合操作:

const customerStats = purchases.reduce((acc, purchase) => {
  const { customer, amount } = purchase;
  // 如果客户还没在统计对象里,就初始化总金额和次数
  if (!acc[customer]) {
    acc[customer] = { total: 0, count: 0 };
  }
  // 累加总金额和次数
  acc[customer].total += amount;
  acc[customer].count += 1;
  return acc;
}, {});

运行这段代码后,customerStats会变成这样:

{
  Alice: { total: 400, count: 2 },
  Bob: { total: 600, count: 2 },
  Charlie: { total: 100, count: 1 },
  David: { total: 400, count: 2 }
}

第二步:计算每位客户的平均消费

有了上面的统计数据,咱们就可以把它转换成只包含平均金额的对象了。这里可以用Object.entries()把对象转成键值对数组,再用map()计算平均值,最后转成对象:

const customerAverages = Object.fromEntries(
  Object.entries(customerStats).map(([customer, stats]) => {
    const average = stats.total / stats.count;
    return [customer, average];
  })
);

完整代码&结果

把上面的步骤整合起来,完整代码就是这样:

const purchases = [
  { customer: "Alice", amount: 250 },
  { customer: "Bob", amount: 400 },
  { customer: "Alice", amount: 150 },
  { customer: "David", amount: 300 },
  { customer: "Bob", amount: 200 },
  { customer: "Charlie", amount: 100 },
  { customer: "David", amount: 100 }
];

const customerStats = purchases.reduce((acc, purchase) => {
  const { customer, amount } = purchase;
  if (!acc[customer]) {
    acc[customer] = { total: 0, count: 0 };
  }
  acc[customer].total += amount;
  acc[customer].count += 1;
  return acc;
}, {});

const customerAverages = Object.fromEntries(
  Object.entries(customerStats).map(([customer, stats]) => [
    customer,
    stats.total / stats.count
  ])
);

console.log(customerAverages);

运行后你会得到想要的结果:

{ Alice: 200, Bob: 300, Charlie: 100, David: 200 }

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 12:28:05