javascript - How to sum nested arrays in JavaScript
问题描述
I'm trying to create a function that sums the total of all the values in an array, even if those values are nested within nested arrays. Like this: countArray(array); --> 28 (1 + 2 + 3 + 4 + 5 + 6 + 7) I tried this recursive function, but it just concatenates.
var countArray = function(array){
var sum=0;
for(let i=0; i<array.length; i++){
if(array[i].isArray){
array[i]=countArray(array[i]);
}
sum+=array[i];
}
return sum;
}
解决方案
使用 展平数组Array.flat()
,然后使用 求和Array.reduce()
:
const countArray = array =>
array.flat(Infinity)
.reduce((sum, n) => sum + n, 0)
console.log(countArray([1, 2, [3, [4, 5], 6], 7]));
推荐阅读
- javascript - 未捕获的 ReferenceError:未定义 timeTicket
- c++ - 使用 std::move 传入一个临时 lambda,或“拉”出一个临时参数,有什么区别?
- google-app-engine - GAE 运行任务冻结
- animation - 禁用 JavaFX 中的所有默认动画
- javascript - 为什么在阿波罗列表更改时每个项目(使用 PureComponent)重新渲染
- apache-spark - 时间戳值在 Apache Spark 中转换为其他格式
- python - 从用户输入创建列表并修改一些元素
- amazon-web-services - 批量配置 Greengrass 组、核心、证书
- data-structures - 如何管理二维数据
- python - Python复杂的分割函数