R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

{ Multi-Dimensional Array Sum }

The Question

You have an array that consists of subarrays that are of varying length. Write a function to find the sum of each element in the array. You may not use any Array methods such as reduce (the only Array method you can use is for checking the type of an element).

mdArraySum([1,2,3,4]); //should return  10
mdArraySum([ [2,4] , [1], [4,2,1] ]); //should return  14
mdArraySum([ 2, [3,4], 5, [-3, [6 , [ 4,5 ] ] ] ]); //should return  26

Note

  • The array elements can also contain arrays as their elements (you can have any amount of nesting)

Approach

  1. The initial sum is 0
  2. Check each element in the array
    • If it is not an array, add it to the sum
    • If it is an array, add the sum of its elements to current sum
  3. Return the final sum after going through every element in the input array

 

How do you calculate the sum of the elements in a sub array of sub arrays? 

Use the function you are writing!

Possible Solution

function mdArraySum(arr) {
  var sum = 0;
    for (var i = 0; i < arr.length ;  i++) {
        if (Array.isArray(arr[i])) {
            sum += mdArraySum(arr[i]);
        } else {
            sum += arr[i];
        }
    }
    return sum;
}

Conclusion  

REPL.IT solutions

 

- Know how recursion/calling a function inside itself works

- Not every problem requires a super long solution (most whiteboarding questions won't)

Multi Dimensional Array Sum

By Seema Ullal

Multi Dimensional Array Sum

Technical interview problem for finding the sum of a multi-dimensional array

  • 1,658