我有如下数组:
const array = [1, 3, 5, 7, 9, 11, 8, 10, 13, 15];
我想对数组中小于10的值求和以求总和变得大于10,如下所示:
const newArray = [16, 20, 18, 13, 15]; // 16 at index 0 is from (1+3+5+7), 20 at index 1 is from (9+11), 18 at index 2 is from (8+10)
这是我尝试过的,我从这里坚持下来:
const minTen = array.reduce((accumulator, currentValue) => {
if (currentValue < 10) {
// 1. Sum value in array to become >= 10
const accumValue = currentValue += // help here please or any othr alternative
// 2. Push new value to the array
accumulator.push(accumValue);
}
return accumulator;
}, []);
console.log(minTen); // [16, 20, 18, 13, 15]
只需检查结果集的最后一个值即可。
const
array = [1, 3, 5, 7, 9, 11, 8, 10, 13, 15],
minTen = array.reduce((accu, value) => {
if (accu[accu.length - 1] < 10) accu[accu.length - 1] += value;
else accu.push(value);
return accu;
}, []);
console.log(minTen); // [25, 11, 18, 13, 15]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句