Weight sum of a nested array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a nested array, arr (nested up to any level) as the only argument.

The function should calculate the weighted sum of the nested array and return that sum.

For calculating nested sum, we multiply a specific element with its level of nesting and add throughout the array.

For example, if the input to the function is −

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

Then the output should be −

const output = 46;

Output Explanation:

The sum will be calculated like this −

(4 * 1) + ( 7 * 1) + (6 * 2) + (1 * 2) + (5 * 3) + (2 * 3) = 46

Example

The code for this will be −

const arr = [4, 7, [6, 1, [5, 2]]];
const findWeightedSum = (arr = [], level = 1, res = 0) => {
   for(let i = 0; i < arr.length; i++){
      if(typeof arr[i] === 'number'){
         res += (level * arr[i]);
      }else if(Array.isArray(arr[i])){
         return findWeightedSum(arr[i], level + 1, res);
      };
   };
   return res;
};
console.log(findWeightedSum(arr));

Output

And the output in the console will be −

46
raja
Published on 19-Mar-2021 05:55:26
Advertisements