当数组中只有一个元素时减少对象数组
Reducing an Array of Objects when there is only one Element in the Array
假设我有这个数组[{num:1}, {num:2}, {num:3}]
. 我可以做到以下几点——
[{num:1}, {num:2}, {num:3}].reduce((a, b) => a.num === undefined? a + b.num : a.num + b.num)
我得到"6",太好了! 但是,如果我的数组只有一个元素(假设我使用循环动态填充我的数组,并且需要在每次迭代期间减少),则[{num:1}]
并执行相同的操作 -
[{num:1}].reduce((a, b) => a.num === undefined? a + b.num : a.num + b.num)
我得到"{num:1}"这是有道理的(如果只有一个元素返回该元素)。
那么有什么方法可以使用reduce
函数并获得上述答案的"正确"答案(即"1")。
我意识到我可以创建自己的函数(循环数组,边走边求和并返回总数),但我有兴趣看看是否可以使用 reduce 函数。
是的,您可以提供初始值 0
:
array.reduce(
(a, b) => a + b.num,
0 // <-- initial value
);
它也适用于空数组(返回0
)。
两个答案:
1)
[{ num: 6 }].reduce(function (a, b) { return a + b.num; }, 0);
// note the starting-value for A, passed into reduce.
2)
[{ num: 6 }].map(el => el.num).reduce((a, b) => a + b, 0);
// I should still pass the starting-value,
// but here I've mapped all of the elements first,
// into the same type that the reduce is expecting,
// thus simplifying the reduce to be a simple add function
相关文章:
- 将数组对象传递到struts2中的操作类
- 如何使用jquery返回php-json数组对象
- 从其名称获取javascript数组对象
- 值未与数组对象绑定
- 如何按数组/对象值的倍数过滤对象数组
- 在表中显示数组对象
- 在数组对象中分组
- 将第二个或多个数组推送到数组对象 AngularJS 中
- 重新排列 JavaScript 数组/对象
- 键上的javascript数组对象过滤器
- handontable:在不更改数据数组/对象的情况下隐藏某些列
- 用于跟踪购物车可用性的Javascript数组/对象/哈希表
- 重建有角度的java脚本数组对象
- 对JSON数组对象进行排序
- 连接与数组对象相关的文本:方式和位置
- 哪些浏览器和版本支持将常见的类数组对象直接传递到fn.apply()
- 如何使用Handlebars循环数组对象和模板
- 是否可以引用JS数组/对象中的另一个元素
- Javascript中的名称索引-数组/对象
- 数组长度不等于数组对象