首页 > 解决方案 > 通过两个不同的键和总和值对数组进行分组

问题描述

我正在使用 React 上的数组,我正在尝试按月和年过滤它,我设法按月进行过滤,但由于某种原因我无法添加年键,这就是我到目前为止所拥有的:

这是我最初拥有的数组:

paid = [
 {amount:155, month:11, year:2020, date:11-11-2020}
 {amount:120, month:11, year:2021, date:05-11-2021}
 {amount:135, month:12, year:2020, date:11-12-2020}
...
]

const group = groupBy(d, (invoices) => invoices.month); //d is the array called "paid"

这是 groupBy 函数:

function groupBy(list, keyGetter) {
    const map = new Map();
    list.forEach((item) => {
      const key = keyGetter(item);
      const collection = map.get(key);
      if (!collection) {
        map.set(key, [parseInt(item.amount)]);
      } else {
        collection.push(parseInt(item.amount));
      }
    });
    return map;
  }

这就是我得到的结果:

grouped = [
 {name:11, values: [155,120...]},
 {name:12, values: [135...]
];

我想要的是将它也按年份分组,例如,第 11 个月不应该有两个值,因为在原始数组上,我拥有的月份是 2020 年的 11 个月和 2021 年的一个,所以结果我想要的是:

grouped = [
 {name:11/2020, values: [155...]},
 {name:11/2021, values: [120...]},
 {name:12/2020, values: [135...]
];

谁能帮我这个?

标签: javascriptarraysreactjsgrouping

解决方案


如果我理解正确,您想对每年每月的所有值求和。我想这会奏效。

// Generate random data.
const genData = () => {
  const d = [];
  for(let i =0; i < 1000; i++) {
    d.push({
      year: Math.round(Math.random() * 10) + 2001,
      month: Math.round(Math.random() * 12),
      amount: Math.round(Math.random() * 100) + 100
    })
  }
  return d;
};

// Sum all data per month per year
const sumData = (d) => {
  const summed = {};
  for(const {year,month,amount} of d) {
    // By using a unique key for each year/month combi you can easily access the
    // intermedeiate result and add another value.
    const key = year + '/' + month;
    
    // If it does not yet exist, create an empty record for this year/month
    if(!(key in summed)) {
      summed[key] = {year,month, sum:0, values:[]};
    }
    
    // Grab the intermediate values and add amount to sum and to values
    summed[key].values.push(amount)
    summed[key].sum += amount;
  }
  return Object.values(summed);
};

// Run all
const d = genData();
console.log(d);
console.log(sumData(d));

推荐阅读