功能汇总

时间:2019-03-11 05:04:59

标签: javascript

有人可以建议一种功能上可行的方法吗?也许和reduce()在一起? 如果名称,重量和研磨相同,则将数量添加到汇总集合中。也许罗达?

let bigOrder = [
  { name: "House Blend", quantity: 1, weight: "250g", grind: "whole-beans" },
  { name: "House Blend", quantity: 3, weight: "250g", grind: "filter" },
  { name: "Decaf", quantity: 1, weight: "250g", grind: "whole-beans" },
  { name: "Colombia", quantity: 4, weight: "250g", grind: "home-espresso" },
  { name: "Decaf", quantity: 1, weight: "250g", grind: "whole-beans" },
  { name: "House Blend", quantity: 2, weight: "250g", grind: "filter" },
  { name: "Colombia", quantity: 1, weight: "250g", grind: "filter" },
  { name: "Decaf", quantity: 1, weight: "250g", grind: "plunger" },
  { name: "Colombia", quantity: 3, weight: "1kg", grind: "whole-beans" },
  { name: "Colombia", quantity: 1, weight: "250g", grind: "whole-beans" },
  { name: "Decaf", quantity: 1, weight: "250g", grind: "plunger" },
  { name: "House Blend", quantity: 5, weight: "1kg", grind: "filter" },
  { name: "House Blend", quantity: 5, weight: "1kg", grind: "filter" },
  { name: "House Blend", quantity: 4, weight: "250g", grind: "filter" }
];

const summariseOrder = () => {
  let summary = [];

  bigOrder.forEach(line => {
    function comparator(a, b) {
      return a.name === b.name && a.weight === b.weight && a.grind === b.grind;
    }

    let index = summary.findIndex(e => comparator(e, line));
    if (index > 0) {
      summary[index].quantity += line.quantity;
    } else {
      summary.push(line);
    }
  });

  return summary;
};

console.log(summariseOrder());

1 个答案:

答案 0 :(得分:2)

您可以使用reduce,方法是根据名称,重量和研磨度创建一个键-如果该键已存在于累加器对象中,则将其添加到该已存在对象中的.quantity中,然后最后,获取该对象的值:

let bigOrder = [
  { name: "House Blend", quantity: 1, weight: "250g", grind: "whole-beans" },
  { name: "House Blend", quantity: 3, weight: "250g", grind: "filter" },
  { name: "Decaf", quantity: 1, weight: "250g", grind: "whole-beans" },
  { name: "Colombia", quantity: 4, weight: "250g", grind: "home-espresso" },
  { name: "Decaf", quantity: 1, weight: "250g", grind: "whole-beans" },
  { name: "House Blend", quantity: 2, weight: "250g", grind: "filter" },
  { name: "Colombia", quantity: 1, weight: "250g", grind: "filter" },
  { name: "Decaf", quantity: 1, weight: "250g", grind: "plunger" },
  { name: "Colombia", quantity: 3, weight: "1kg", grind: "whole-beans" },
  { name: "Colombia", quantity: 1, weight: "250g", grind: "whole-beans" },
  { name: "Decaf", quantity: 1, weight: "250g", grind: "plunger" },
  { name: "House Blend", quantity: 5, weight: "1kg", grind: "filter" },
  { name: "House Blend", quantity: 5, weight: "1kg", grind: "filter" },
  { name: "House Blend", quantity: 4, weight: "250g", grind: "filter" }
];

const summariseOrder = arr => Object.values(arr.reduce(
  (a, obj) => {
    const key = `${obj.name}_${obj.weight}_${obj.grind}`;
    if (!a[key]) a[key] = obj;
    else a[key].quantity += obj.quantity;
    return a;
  }, {}
));
console.log(summariseOrder(bigOrder));