【问题标题】:Calling reduce to sum array of objects returns NaN调用 reduce 对对象数组求和返回 NaN
【发布时间】:2021-04-09 22:28:58
【问题描述】:

我有类似这样的代码:

var temp = [ { "y": 32 }, { "y": 60 }, { "y": 60 } ];
var reduced = temp.reduce(function(a, b) {
  return a.y + b.y;
});

console.log(reduced); // Prints NaN

为什么打印NaN 而不是152

【问题讨论】:

  • 解释问题 - 一旦你返回第一个总和,a 的类型将是一个数字 - 它没有 y 属性
  • 查看reduce函数的回调参数,它们是什么?
  • 这能回答你的问题吗? Javascript reduce on array of objects

标签: javascript reduce


【解决方案1】:

您可以使用一个起始值,然后只从数组中添加一个值。

var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}];

var reduced = temp.reduce(function (r, a) {
        return r + a.y;
        //    ^^^ use the last result without property
    }, 0);
//   ^^^ add a start value
console.log(reduced) // r

【讨论】:

  • 一个衬里 const 减少 = temp.length ? temp.reduce((r, a) => { return r + a.y; }, 0) : 0;
  • @webmaster,更短的,空数组取reduce的起始值:const reduced = temp.reduce((r, { a }) => r + a, 0);
【解决方案2】:

简短的解决方案:将集合映射到整数集合,并减少它

var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}];

var reduced = temp
                .map(function(obj) { return obj.y; })
                .reduce(function(a, b) { return a + b; });

console.log(reduced);

【讨论】:

    猜你喜欢
    • 2013-01-03
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 2021-10-25
    • 2019-11-10
    • 2021-03-20
    • 2022-01-15
    相关资源
    最近更新 更多