如何合并同仓库重复产品并计算总数量与加权平均价格
合并同仓库重复产品并计算加权平均价格
需求说明
合并同一仓库下的重复产品,计算总数量,并通过公式 ((总数量 / 100) * 总金额) 生成新的加权平均价格(注:总金额为该产品在对应仓库下所有条目「价格×数量」的总和)
给定库存数据
let inventories = [ { product: 'laptop', price: 50, warehouse: 'Kismayu', quantity: 6 }, { product: 'phone', price: 20, warehouse: 'Mogadishu', quantity: 3 }, { product: 'notebook', price: 30, warehouse: 'Mogadishu', quantity: 2 }, { product: 'phone', price: 40, warehouse: 'Mogadishu', quantity: 1 }, { product: 'phone', price: 60, warehouse: 'Hargeisa', quantity: 3 }, ]
解决方案代码
const mergeInventories = (inventories) => { // 用「产品名-仓库名」作为唯一键,分组存储同仓库同产品的库存 const groupedInventory = {}; for (const item of inventories) { const key = `${item.product}-${item.warehouse}`; if (!groupedInventory[key]) { // 首次出现的条目,初始化分组数据 groupedInventory[key] = { ...item, totalAmount: item.price * item.quantity }; } else { // 重复条目,累加数量和总金额 groupedInventory[key].quantity += item.quantity; groupedInventory[key].totalAmount += item.price * item.quantity; } } // 转换为数组并计算最终价格 return Object.values(groupedInventory).map(item => ({ product: item.product, price: (item.quantity / 100) * item.totalAmount, warehouse: item.warehouse, quantity: item.quantity })); }; // 执行函数并输出结果 const mergedResult = mergeInventories(inventories); console.log(mergedResult);
最终输出结果
[ { product: 'laptop', price: 50, warehouse: 'Kismayu', quantity: 6 }, { product: 'phone', price: 24, warehouse: 'Mogadishu', quantity: 4 }, { product: 'notebook', price: 30, warehouse: 'Mogadishu', quantity: 2 }, { product: 'phone', price: 60, warehouse: 'Hargeisa', quantity: 3 }, ]
逻辑说明
- 分组规则:通过「产品名+仓库名」的组合作为唯一标识,确保只合并同一仓库下的同产品条目
- 数据累加:对每组内的库存数量直接累加,同时计算该组的总金额(所有条目「价格×数量」的总和)
- 价格计算:严格按照给定公式生成新的加权平均价格,最终整理为需求格式的数组
内容的提问来源于stack exchange,提问作者Ahmed Ibrahim
相关产品推荐
相关产品推荐

