Find the sum of numbers in an array

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.

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

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:

You can play around with the code on fiddle

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