Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum all integers in a multidimensional array javascript

Let's say I have this:

function arrSum(){
  *code here*
}

How do I write the arrSum function such that it can sum all the integers within a multidimensional array (of variable depth).

I.e.

arrSum([2, 5, [4, 6], 5]) === 22;

I know there must be an answer to this somewhere but I really can't find it. If this is a duplicate please let me know.

like image 952
VoA Avatar asked Nov 12 '15 05:11

VoA


People also ask

How do you find the sum of all numbers in an array?

Approach to Find the Sum of All Elements in an ArrayInitialize a variable sum to store the total sum of all elements of the array. Traverse the array and add each element of the array with the sum variable. Finally, return the sum variable.

How do you sum all elements in a 2D array?

Let's see how to find the sum of the 2D array using the map function. Initialize the 2D array using lists. Pass the function sum and 2D array to the map function. Find the sum of resultant map object and print it.

How do you find the total number of elements in a multidimensional array?

The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.


1 Answers

Simply you can write a function like this with recursion

function arrSum(arr) {
  var sum = 0;
  // iterate array using forEach, better to use for loop since it have higher performance
  arr.forEach(function(v) {
    // checking array element is an array
    if (typeof v == 'object')
      // if array then getting sum it's element (recursion)
      sum += arrSum(v);
    else
      // else adding the value with sum
      sum += v
  })
  // returning the result
  return sum;
}

console.log(arrSum([2, 5, [4, 6], 5]) === 22);

Using for loop

function arrSum(arr) {
  var sum = 0;
  for (var i = 0; i < arr.length; i++) {
    if (typeof arr[i] == 'object')
      sum += arrSum(arr[i]);
    else
      sum += arr[i];
  }
  return sum;
}

console.log(arrSum([2, 5, [4, 6], 5]) === 22);
like image 147
Pranav C Balan Avatar answered Sep 24 '22 19:09

Pranav C Balan