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.

9
  • 1
    Welcome! You are missing a comma (,) and are inconsistent... [5, 7, [4, [2], 8, [1, 3], 2], [9, []], 1, 8]. Commented Oct 26, 2020 at 15:32
  • is this a homework? Commented Oct 26, 2020 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) Commented Oct 26, 2020 at 15:36
  • Yes. it is a homework;) And I have to use recursion Commented Oct 26, 2020 at 15:41
  • 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. Commented Oct 26, 2020 at 15:54

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

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;
}

1 Comment

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.)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.