RussellPhotog
RussellPhotog

Reputation: 13

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.

Upvotes: 1

Views: 296

Answers (4)

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

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

Upvotes: 2

dannyadam
dannyadam

Reputation: 4170

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

Upvotes: 0

Pac0
Pac0

Reputation: 23174

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

Upvotes: 2

gus
gus

Reputation: 117

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

Upvotes: 1

Related Questions