Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Contact us
Hide Buttons

Calculate the average of a nested array

Problem description:

The following nested array contains some invalid entries (which are not numbers). We also want to filter those entries in our average calculation.

var nestedArray = [ 1, 2, 3, [4, 5, 6,'abc', [7, 8, 9, []]] ];

Input : An array
Output : A number

Logic :

  • We will use recursion to solve this problem.
  • For each element in an array call the callback
    • If an element is a number then add the value to sum
    • Else if an element is an array then call the callback recursively.

Solution :

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *