如何按月然后按客户将一系列产品销售分组

时间:2019-06-19 12:23:32

标签: javascript arrays sorting

一年中,我为许多客户存储了一系列不同的产品销售信息,这些数据存储在几个月内。我希望能够将一年内购买的客户分组为一个列。

var sales = [
  ["Jan", "Customer 1", "Product 1", 538]
  ["Feb", "Customer 1", "Product 1", 0]
  ["March", "Customer 1", "Product 1", 252]
  ["Apr", "Customer 1", "Product 1", 0]
  ["May", "Customer 1", "Product 1", 630]
  ["June", "Customer 1", "Product 1", 945]
  ["July", "Customer 1", "Product 1", 0]
  ["Aug", "Customer 1", "Product 1", 630]
  ["Sept", "Customer 1", "Product 1", 756]
  ["Oct", "Customer 1", "Product 1", 0]
  ["Nov", "Customer 1", "Product 1", 0]
  ["Dec", "Customer 1", "Product 1", 630]
  ["Jan", "Customer 1", "Product 2", 50]
  ["Feb", "Customer 1", "Product 2", 630]
  ...
]

我尝试将独特的产品分组,然后获得独特的客户,然后获得独特的产品,如下所示,但我不知道如何从这里继续前进。

// Get a list of unique products
var products = sales.map(item => {
  return item[2];
}).filter((val, index, self) => {
  return self.indexOf(val) === index;
});
console.log(products);

// Ge a list of unique customers
var targets = sales.map(item => {
  return item[1]
}).filter((val, index, self) => {
  return self.indexOf(val) === index
});
console.log(targets);

我想要一组按客户和产品分组的对象

[
  {
    "customer": "Customer 1",
    "product": "Product 1",
    "jan" 538,
    "feb": 0,
    "march": 252
    ...
  },
  {
    "customer": "Customer 1",
    "product": "Product 2",
    "jan" 50,
    "feb": 630,
    ...
  }
]

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

您可以使用来自客户和产品的组合键,然后为该对象获取哈希表。最后,从哈希表中获取这些值。

var sales = [["Jan", "Customer 1", "Product 1", 538], ["Feb", "Customer 1", "Product 1", 0], ["March", "Customer 1", "Product 1", 252], ["Apr", "Customer 1", "Product 1", 0], ["May", "Customer 1", "Product 1", 630], ["June", "Customer 1", "Product 1", 945], ["July", "Customer 1", "Product 1", 0], ["Aug", "Customer 1", "Product 1", 630], ["Sept", "Customer 1", "Product 1", 756], ["Oct", "Customer 1", "Product 1", 0], ["Nov", "Customer 1", "Product 1", 0], ["Dec", "Customer 1", "Product 1", 630], ["Jan", "Customer 1", "Product 2", 50], ["Feb", "Customer 1", "Product 2", 630]],
    result = Object.values(sales.reduce((r, [month, customer, product, value]) => {
        var key = [customer, product].join('|');
        r[key] = r[key] || { customer, product };
        r[key][month.toLowerCase()] = value;
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }