gpt4 book ai didi

javascript - 在javascript中分组和求和哈希数组

转载 作者:行者123 更新时间:2023-12-04 02:19:27 28 4
gpt4 key购买 nike

我有以下哈希数组,并希望将其转换为类似于帖子底部的数组。

var responseData = [
{deviceType: "Smartphone", deviceCount: 14},
{deviceType: "Tablet", deviceCount: 11},
{deviceType: "Notebook", deviceCount: 3},
{deviceType: "Desktop", deviceCount: 2},
{deviceType: "Smartphone", deviceCount: 1},
{deviceType: "Tablet", deviceCount: 10},
{deviceType: "Notebook", deviceCount: 30},
{deviceType: "Desktop", deviceCount: 20}
];

function dataMapper(responseData){
let series = [];
if(responseData && responseData.length){
responseData.forEach(function(resource){
existingElement = series.filter(function (item) {
return item.deviceType === resource.deviceType;
});
if (existingElement) {
deviceCount = existingElement[0].deviceCount + resource.deviceCount;
existingElement[0].deviceCount = deviceCount
}else{
series[0].push({deviceType: resource.deviceType, y: resource.deviceCount});
}
});
}
return series
}

console.log(dataMapper(responseData))

我想把它转换成:

var expectedResult = [
{deviceType: "Smartphone", deviceCount: 15},
{deviceType: "Tablet", deviceCount: 21},
{deviceType: "Notebook", deviceCount: 33},
{deviceType: "Desktop", deviceCount: 22}
];

最佳答案

使用 ES6 Map 和 reduce:

const responseData = [{deviceType: "Smartphone", deviceCount: 14},{deviceType: "Tablet", deviceCount: 11},{deviceType: "Notebook", deviceCount: 3},{deviceType: "Desktop", deviceCount: 2},{deviceType: "Smartphone", deviceCount: 1},{deviceType: "Tablet", deviceCount: 10},{deviceType: "Notebook", deviceCount: 30},{deviceType: "Desktop", deviceCount: 20}];

const result = Array.from(
responseData.reduce(
(acc, o) => (acc.get(o.deviceType).deviceCount += o.deviceCount, acc),
new Map(responseData.map( ({deviceType}) => [deviceType, {deviceType, deviceCount: 0} ] ))
).values()
);

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

关于javascript - 在javascript中分组和求和哈希数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48866924/

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