使用Javascript,如何计算一个值在对象数组中出现的次数,同时添加出现次数值

问题描述 投票:0回答:1

我有一系列看起来与此类似的对象,

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
但无法同时添加两个值。

javascript reactjs arrays object reduce
1个回答
0
投票

正如您所提到的,这可以通过

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);

© www.soinside.com 2019 - 2024. All rights reserved.