gpt4 book ai didi

typescript 按特定值减少对象数组

转载 作者:行者123 更新时间:2023-12-05 01:16:30 25 4
gpt4 key购买 nike

我有这个:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com