2 回答
TA贡献1854条经验 获得超8个赞
您的问题不清楚,但这里有一个使用 .它还跟踪遇到的每个键的总数,以防数组中并非所有对象都具有相同的键。您希望结果数组采用的格式尚不清楚,但我展示了一个根据调用结果计算平均值的示例。reduce()reduce()
const arr = [
{count1: 3, count2: 2},
{count1: 4, count2: 10},
{count1: 3, count3: 2}
];
const sumObj = arr.reduce((a, o) => (
Object.entries(o).forEach(([k, v]) => (
a[k] = {...a[k] ?? {sum: 0, total: 0}}
, a[k]['sum'] += v
, a[k]['total'] += 1)
), a), {});
console.log(sumObj);
const averageArr = Object.entries(sumObj).map(([k, {sum, total}]) => ({key: k, average: sum/total}));
console.log(averageArr);
TA贡献1796条经验 获得超7个赞
您可以使用map和reduce,就像给定多个键一样:
const exampleArray = [{swag: 3, count: 2}, {swag: 4, count: 10}];
// converting into array with only the key you want to use
const countArray = exampleArray.map((element) => element.count); // an array with just {count: value} elements in them.
// ... now reduce like normally
添加回答
举报