javascript 如何合并同一仓库的重复产品并得到平均价格

xuo3flqw  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(126)

将同一仓库的重复产品合并,得到总数量,按平均价格((总数量/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 },
]

最终输出:

[
    { 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 },
  ]
shyt4zoc

shyt4zoc1#

我对'摩加迪沙'和'phone'的平均价格有点困惑。您期望的平均价格是24,而20和40的平均价格是30。假设30是正确的计算方法,下面是一个函数式编程解决方案:

const 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 },
]

let result = Object.entries(inventories.reduce((acc, obj) => {
  if(!acc[obj.warehouse]) acc[obj.warehouse] = {};
  if(!acc[obj.warehouse][obj.product]) acc[obj.warehouse][obj.product] = [];
  acc[obj.warehouse][obj.product].push([obj.price, obj.quantity])
  return acc;
}, {})).map(wp => [wp[0], Object.entries(wp[1]).map(pp => ({
  warehouse: wp[0],
  product: pp[0],
  price: pp[1].reduce((a, pq) => a + pq[0], 0) / pp[1].length,
  quantity: pp[1].reduce((a, pq) => a + pq[1], 0)
}))]).flat().flat().filter(val => typeof val === 'object');
console.log(result);

输出:

[
  {
    "warehouse": "Kismayu",
    "product": "laptop",
    "price": 50,
    "quantity": 6
  },
  {
    "warehouse": "Mogadishu",
    "product": "phone",
    "price": 30,
    "quantity": 4
  },
  {
    "warehouse": "Mogadishu",
    "product": "notebook",
    "price": 30,
    "quantity": 2
  },
  {
    "warehouse": "Hargeisa",
    "product": "phone",
    "price": 60,
    "quantity": 3
  }
]

相关问题