Write an function to sum the array of array in JavaScript

Question:

Write an function to sum the array of array in JavaScript. Here is the input array:

const arr = [
  [1, 2],
  [3, 4, 5],
  [5, 6, 7, 8],
];

 

Answer:

function sum(arr) {
  let sum = 0;

  function helper(arrPeram) {
    for (let value of arrPeram) {
      if (value instanceof Array) {
        helper(value);
      } else {
        sum = sum + value;
      }
    }
  }

  helper(arr);
  return sum;
}
console.log(sum(arr)); //41

 

Explanation:

  1. Initialization: The function initializes a sum variable to 0.
  2. Helper Function: The helper function is defined within sum. This function iterates over each element of the input array (arrPeram).
  3. Recursion:
    • If an element is an array (value instanceof Array), the function calls itself recursively (helper(value)) to sum the elements of this nested array.
    • If the element is not an array, it adds the element's value to sum.
  4. Calling the Helper: The helper function is called with the initial array (arr), starting the summing process.
  5. Return Result: Finally, the sum function returns the accumulated sum.

Output:
When you run console.log(sum(arr));, the function sums all numbers in the nested arrays and outputs 41.