1

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.

  • 1
    Welcome! You are missing a comma (,) and are inconsistent... `[5, 7, [4, [2], 8, [1, 3], 2], [9, []], 1, 8]`. – iAmOren Oct 26 '20 at 15:32
  • is this a homework? – ibrahim mahrir Oct 26 '20 at 15:35
  • 1
    It IS easy without recursion: `[5, 7, [4, [2], 8, [1, 3], 2], [9, []], 1, 8].flat(Infinity).reduce((sum, value)=>sum+value)` – iAmOren Oct 26 '20 at 15:36
  • Yes. it is a homework;) And I have to use recursion – RussellPhotog Oct 26 '20 at 15:41
  • You want to sum all the numbers or just the numbers at the array level? –  Oct 26 '20 at 15:46
  • @expressjs123 since "recursion" is mentionned, it seems highly probably that OP has to sum every element, at any level. – Pac0 Oct 26 '20 at 15:47
  • @expressjs123 I need to calculate the sum of all the numbers. So the function has to call it self getting into each level of the SumTree. And the other condition was not to declare functions within the main function. As I understood this only function expression is accepted. – RussellPhotog Oct 26 '20 at 15:52
  • 2
    @ibrahimmahrir . The only person I'm cheating here is myself. But I need it. That's the way I learn. I'm going to give it a try anyways, that's actually what I'm doing now. digging into recursion and trying to understand how it can be done here. – RussellPhotog Oct 26 '20 at 15:54
  • in the recursion, test if argument is an array - loop over it's elements and call the recursion with each, if a number - add to sum. – iAmOren Oct 26 '20 at 15:58

4 Answers4

2

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 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:

const sumArray = arr => arr.reduce((sum, item) =>
  sum + (Array.isArray(item) ? sumArray(item) : item)
, 0);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
2

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).
Pac0
  • 21,465
  • 8
  • 65
  • 74
1

I think this might be what you're looking for 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;
}
gus
  • 117
  • 1
  • 6
  • Two things. Please don't post code-only answers; answers should also explain the code and problems with the OP's approach. And don't repost answers from another question, instead offering it as a possible duplicate, with a link in the comments. (With enough reputation, you will also gain the privilege of adding close votes for duplicates.) – Scott Sauyet Oct 26 '20 at 19:50
0

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. For the rest of the array, sum is recursively applied.

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
dannyadam
  • 3,950
  • 2
  • 22
  • 19