简体   繁体   English

使用递归计算数组中 arrays 的总和

[英]calculate sum of the arrays within array using recursion

Could anyone help me do this task?谁能帮我完成这个任务? I don't get how to do it.我不知道该怎么做。 I need to find the sum of this array using recursion.我需要使用递归找到这个数组的总和。 [ 5,7 [ 4, [2], 8, [1,3], 2 ], [ 9, [] ], 1, 8 ]

I would probably be able to find the sum if it was a regular array, but this one here is a bit confusing having arrays within array.如果它是一个常规数组,我可能能够找到总和,但是这里的这个有点令人困惑,因为数组中有 arrays。

It is pretty straightforward using recursion, just loop over the array and for each element check if it is another array, if so call the function on it and add its result to the sum, if not (meaning if it is a number) then just add the element to the sum, like so:使用递归非常简单,只需遍历数组并为每个元素检查它是否是另一个数组,如果是,则调用 function 并将其结果添加到总和,如果不是(意味着它是否是一个数字)则只需将元素添加到总和中,如下所示:

function sumArray(arr) {                          // takes an array and returns its sum
  let sum = 0;                                    // the sum

  for(let i = 0; i < arr.length; i++) {           // for each element in the array
    if(Array.isArray(arr[i])) {                   // if the element is an array
      sum += sumArray(arr[i]);                    // call the function 'sumArray' on it to get its sum then add it to the total sum
    } else {                                      // otherwise, if it is a number
      sum += arr[i];                              // add it to the sum directly
    }
  }

  return sum;
}

BTW, the above code can be shortened drastically using the array method reduce , some arrow functions and a ternary operator instead of if / else like so:顺便说一句,上面的代码可以使用数组方法reduce 、一些箭头函数和一个三元运算符而不是像这样的if / else来大大缩短:

const sumArray = arr => arr.reduce((sum, item) =>
  sum + (Array.isArray(item) ? sumArray(item) : item)
, 0);

Sketch of the solution:解决方案示意图:

"The function" that calculates the total should do a regular loop over the array parameter.计算总数的“函数”应该对数组参数进行定期循环。

For each element:对于每个元素:

  • if it's a number then add it to the total (normal case),如果它是一个数字,则将其添加到总数中(正常情况),
  • but if it's an array, then add the result returned by "the function" applied on this inner array (recursive case).但如果它是一个数组,则添加应用于此内部数组的“函数”返回的结果(递归情况)。

I think this might be what you're looking for Recursion - Sum Nested Array我认为这可能是您要查找的内容Recursion - Sum Nested Array

function sumItems(array) {
  let sum = 0;
  array.forEach((item) => {
    if(Array.isArray(item)) {
     sum += sumItems(item);
    } else {
    sum += item;
    }
  })
  return sum;
}

One way to solve this is by breaking the array into two parts, calculating the sum of each part, and then adding the results.解决这个问题的一种方法是将数组分成两部分,计算每部分的总和,然后将结果相加。

For example, the implementation below separates the array into its first element and all the remaining elements.例如,下面的实现将数组分成它的第一个元素和所有剩余元素。 If the first element is an array, sum is recursively applied, otherwise the value is used directly.如果第一个元素是数组,则递归应用sum ,否则直接使用该值。 For the rest of the array, sum is recursively applied.对于数组的rest,递归sum

const sum = function(array) {
    if (array.length === 0) return 0;
    let first = array[0];
    if (Array.isArray(first))
        first = sum(first);
    const rest = sum(array.slice(1));
    return first + rest;
}

const array = [ 5, 7, [ 4, [ 2 ], 8, [ 1, 3 ], 2 ], [ 9, [] ], 1, 8 ];
console.log(sum(array));  // 50

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM