打字稿按特定值减少对象数组

时间:2018-11-27 10:40:41

标签: typescript

我有这个:

0: {orderType: "orderType1", orderCount: 0, orderDate: 47}
1: {orderType: "orderType1", orderCount: 21, orderDate: 47}
2: {orderType: "orderType1", orderCount: 3, orderDate: 47}
3: {orderType: "orderType1", orderCount: 5, orderDate: 48}
4: {orderType: "orderType1", orderCount: 32, orderDate: 48}
5: {orderType: "orderType1", orderCount: 12, orderDate: 48}

我想实现这一目标:

0: {orderType: "orderType1", orderCount: 24, orderDate: 47}
1: {orderType: "orderType1", orderCount: 49, orderDate: 48}

基本上我想通过结合基于orderDate的orderCount来“组合”或“减少”条目。

在这里道歉,如果结合或减少不是正确的条件。

2 个答案:

答案 0 :(得分:1)

比我聪明的人可能会更简洁地执行此操作,但是如果我对数据进行分组然后进行缩减,则可以得到所需的结果。

我觉得这可以用更少的步骤完成:

function setFilter(value, index, self) { 
    return self.indexOf(value) === index;
}

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}

const data = [
    { orderType: "orderType1", orderCount: 0, orderDate: 47 },
    { orderType: "orderType1", orderCount: 21, orderDate: 47 },
    { orderType: "orderType1", orderCount: 3, orderDate: 47 },
    { orderType: "orderType1", orderCount: 5, orderDate: 48 },
    { orderType: "orderType1", orderCount: 32, orderDate: 48 },
    { orderType: "orderType1", orderCount: 12, orderDate: 48 }
];

const groupedData = groupBy(data, 'orderDate');
const reducedData = [];

for (let key in groupedData) {
    let initialValue = 0;
    let sum = groupedData[key].reduce((accumulator, currentValue) => {
        return accumulator + currentValue.orderCount;
    },initialValue)

    reducedData.push({
        orderType: groupedData[key][0].orderType,
        orderCount: sum,
        orderDate: key
    });
}

console.log(reducedData);

这没有考虑orderType,我认为应该这样做。

答案 1 :(得分:0)

以下是一个(略短的)版本,也使用了reduce:

NULL