我有一系列看起来与此类似的对象,
const data = [
{id: 1, type: full, occurrences: 2},
{id: 2, type: partial, occurrences: 1},
{id: 3, type: partial, occurrences: 1}
];
我将如何添加获取部分或完整数据类型的次数,同时还要考虑到出现的次数。
expected result = [{type: full, occurrences: 2}, {type: partial, occurrences: 2}];
我尝试使用
reduce
但无法同时添加两个值。
Array.protoype.reduce
函数来实现:
const data = [
{ id: 1, type: 'full', occurrences: 2 },
{ id: 2, type: 'partial', occurrences: 1 },
{ id: 3, type: 'partial', occurrences: 1 },
];
const result = data.reduce((accumulator, current) => {
const found = accumulator.find((item) => item.type === current.type);
found ? found.occurrences += current.occurrences : accumulator.push({ type: current.type, occurrences: current.occurrences });;
return accumulator;
}, []);
console.log(result);