当数组中只有一个元素时减少对象数组

Reducing an Array of Objects when there is only one Element in the Array

本文关键字:数组 对象 有一个 元素      更新时间:2023-09-26

假设我有这个数组[{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