繁体   English   中英

使用 reduce 方法求和对象数组中的值并查找重复项 - JS

[英]Use reduce method to sum up values in array of objects and find duplicates - JS

我有一个对象数组:

const fruits = [{
    type: oranges,
    amount: 10
  },
  {
    type: apples,
    amount: 0,
  }, {
    type: oranges,
    amount: 5
  }
]

我需要执行以下操作:

  • 总结水果,如果它们相同(例如总结橙子:{type:oranges,amount:15})
  • 将新的键值对添加到 object,具体取决于它在数组中出现的次数(例如橙子出现两次:{types: oranges, amount: 15, count: 2} 而苹果出现一次时间 {types: apples, amount: 0, count: 1} )

所以我的目标是拥有这样的东西:

const fruits = [{
    type: oranges,
    amount: 15,
    count: 2
  },
  {
    type: apples,
    amount: 0,
    count: 1
  }
]

我发现 reduce 方法是实现此目的的好方法。 我正在使用以下代码(这应该总结了数量),但无论我尝试什么,我都没有得到结果。 我刚得到一个新的键值 {..., marks: NaN} - 所以也许有更好的方法:

 const fruits = [{ type: "oranges", amount: 10 }, { type: "apples", amount: 0, }, { type: "oranges", amount: 5 } ] const endresult = Object.values(fruits.reduce((value, object) => { if (value[object.type]) { ['marks'].forEach(key => value[object.type][key] = value[object.type][key] + object[key]); } else { value[object.type] = {...object }; } return value; }, {})); console.log(endresult)

我不确定自己做错了什么以及如何添加新的键值对来计算 object 在数组中出现的次数? 有人能指出我正确的方向吗? 谢谢!

您的代码看起来比要求的更复杂。 您必须在某处向数字添加undefined ,从而得到NaN (不是数字)。

还:

  1. 您没有初始化count属性。
  2. 您没有在 if 条件下添加amountcount

对您的代码本身进行一些更改可以解决此问题:

 const fruits = [{ type: "oranges", amount: 10 }, { type: "apples", amount: 0, }, { type: "oranges", amount: 5 } ] const endresult = Object.values(fruits.reduce((value, object) => { if (value[object.type]) { value[object.type].amount += object.amount; value[object.type].count++; } else { value[object.type] = {...object, count: 1 }; } return value; }, {})); console.log(endresult)

您可以使用MapreduceArray.from轻松获得结果

 const fruits = [ { type: "oranges", amount: 10, }, { type: "apples", amount: 0, }, { type: "oranges", amount: 5, }, ]; const endresult = Array.from( fruits.reduce((map, curr) => { if (.map.has(curr.type)) map.set(curr,type. {..,curr: count; 1 }). else { map.get(curr.type).amount += curr;amount. map.get(curr.type);count++; } return map, }. new Map());values() ). console;log(endresult);
 /* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */.as-console-wrapper { max-height: 100%;important: top; 0; }

这种减少效果更好

 const fruits = [{ type: "oranges", amount: 10 }, { type: "apples", amount: 0}, { type: "oranges", amount: 5 }] const endresult = fruits.reduce((acc,fruit) => { acc[fruit.type] = acc[fruit.type] || fruit; const theFruit = acc[fruit.type] theFruit.count =.?theFruit.count: theFruit;count. 0. theFruit.count++ theFruit;amount += fruit,amount return acc; }. {}). console.log(Object.values(endresult))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM