typescript 按特定值减少对象数组

标签 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 来“组合”或“减少”条目。

抱歉,如果 combine 或 reduce 不是正确的术语。

最佳答案

比我聪明的人可能会更简洁地做到这一点,但如果我对数据进行分组然后减少它,我可以得到想要的结果。

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

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,我觉得应该考虑。

关于 typescript 按特定值减少对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53497822/

相关文章:

javascript - Node 看不到模块

javascript - JSON 对象属性转换为 JSON 对象名称

javascript - es6可以导入commonjs模块吗?

typescript - @types/arcgis-js-api 在 angular 5 应用程序中

javascript - 使用 Typescript 进行接口(interface)类型检查

typescript 枚举和外部模块(browserify)

javascript - 如何在 TypeScript 声明文件中设置默认类属性值?

typescript - 与 --build 开关一起使用时,tsc typescript 3.5 中的未知构建选项 '-p'

javascript - 我需要如何更改这些 TypeScript mixin 类型定义才能允许定义允许类扩展特征的 mixin?

json - 将用户数据添加到本地存储只工作一次,此后被添加的对象被简单地覆盖? ( Angular 10+)