【问题标题】:Group by and perform a multiple operation to another array and push to a new array分组并对另一个数组执行多重操作并推送到新数组
【发布时间】:2020-09-29 02:37:57
【问题描述】:

我想通过对另一个对象数组的值进行多次操作,通过与一些 key 分组来将一个值推送到一个新数组。

我的数组为:

var newArray = [{ltd: "Cpt", stdSquare: "0.35", error: "0.65"},
 {ltd: "Cpt", stdSquare: "0.16", error: "0.84"},
 {ltd: "Ant", stdSquare: "0.21", error: "0.79"},
 {ltd: "Ant", stdSquare: "0.79", error: "0.21"}];

在下面这个减少函数中,我想通过与ltd 分组来将stdSquare 的值相加并推送到results 数组。

但这给了我一个错误:

未捕获的类型错误:map.get 不是函数

var results = [];
const sums = [
  ...newArray.reduce(
    (map, item) => {

      const { ltd: key, stdSquare } = item;

      let sumOfstdSquare = 0;
      const prev = map.get(key);
              
        sumOfstdSquare += stdSquare;
       
        results.push({ltd, sumOfstdSquare});
 
      
      return results
    },
    new Map()
  ).values()
]

期望的输出:

[
  {ltd:"Cpt", sumOfstdSquare: 0.51},
  {ltd:"Ant", sumOfstdSquare: 1.00}
]

【问题讨论】:

  • 似乎是对reduce的错误使用。 map.get is not a function 因为您在reduce 函数中返回results,它是一个数组而不是映射并且没有.get 方法

标签: javascript


【解决方案1】:

如果我理解正确,您希望:

  • 对所有标准平方求和
  • 按有限公司分组

这是一个例子:
在这个答案中我不修改原点,我创建一个新数组grouped

如果你想让原点指向结果 jusr 使用newArray = [...groupd];

var newArray = [
 {ltd: "Cpt", stdSquare: "0.35", error: "0.65"},
 {ltd: "Cpt", stdSquare: "0.16", error: "0.84"},
 {ltd: "Ant", stdSquare: "0.21", error: "0.79"},
 {ltd: "Ant", stdSquare: "0.79", error: "0.21"}];
 
 const grouped = newArray.reduce((ret, val) => {
  const ltd = val.ltd
  const index = ret.findIndex(item=>item.ltd == ltd)
  if(index == -1) {
    return [...ret, {ltd: val.ltd, stdSquare: parseFloat(val.stdSquare)}]
  }
  else {
   const newItem = {ltd: val.ltd,stdSquare: parseFloat(val.stdSquare) + ret[index].stdSquare};
   ret.splice(index, 1, newItem)
   return ret
  }
  
 },
 [])
 
 console.log(grouped)

【讨论】:

  • 这似乎不起作用,它只是打印输入中的内容...我想与 ltd 分组并将结果相加,在一个数组中。
  • 我想我在这里错过了一些东西.. 代码返回一个组图和一个总和。你能添加你想要的输出吗?
  • 我已经用所需的输出修改了我的帖子,以显示示例,但我可以从缩减函数返回任意数量的项目。
猜你喜欢
  • 1970-01-01
  • 2017-06-22
  • 2017-07-06
  • 1970-01-01
  • 2020-09-05
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多