This is a very simple question to ask someone to Find the sum of numbers in an array.

The expectation is that the candidate will know how to run a for loop on the array and use a variable to add the numbers and return the total.

Here is straightforward solution to this question.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let myArrayOfNumbers = [1,2,3,4,5]; function sumNumbers(arr){ let arrayLength = arr.length; let total = 0; for(i=0;i<arrayLength;i++){ total += arr[i]; } return total; } console.log(sumNumbers(myArrayOfNumbers)); |

You can try out this solution on Fiddle

#### Sum numbers in an array that has element which is an array

Now what makes this question more interesting is lets say the array has nested arrays like this

1 |
let myArrayOfNumbers = [2,4,[1,2,[3,[1,1],2,[4,3,[2,2]],4],1],3]; |

How would you return the sum of numbers of the array above?

It is not very difficult.

While running the loop on every element we need to check if the “Element of the array is Array”. If yes, than call the same function. Else continue adding the elements in the total, This concept of calling the same function by itself is called “Recursion” in Javascript.

Here is the complete solution:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let myArrayOfNumbers = [2,4,[1,2,[3,[1,1],2,[4,3,[2,2]],4],1],3]; function sumArray(arrayObj){ total = 0; for (num in arrayObj) { // For loop to run for each array element if(arrayObj[num].constructor === Array){ // check if array element is array & if yes call summArray function again by passing array as an parameter total += sumArray(arrayObj[num]); }else{ //else keep adding array element value in sum variable total += arrayObj[num]; } } return total; } console.log(sumArray(myArrayOfNumbers)); |

You can play around with the code on fiddle

This is really tricky. Not everyone can solve this very easily.