Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Weight sum of a nested array in JavaScript
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 weighted sum, we multiply each element with its level of nesting and add throughout the array. Elements at the first level are multiplied by 1, second level by 2, and so on.
Problem Example
For example, if the input to the function is:
const arr = [4, 7, [6, 1, [5, 2]]];
Then the output should be:
46
Output Explanation
The sum will be calculated like this:
(4 * 1) + (7 * 1) + (6 * 2) + (1 * 2) + (5 * 3) + (2 * 3) = 46
Where:
- Elements 4 and 7 are at level 1
- Elements 6 and 1 are at level 2 (inside one nested array)
- Elements 5 and 2 are at level 3 (inside two nested arrays)
Solution Using Recursion
The code for this will be:
const arr = [4, 7, [6, 1, [5, 2]]];
const findWeightedSum = (arr = [], level = 1) => {
let result = 0;
for(let i = 0; i < arr.length; i++){
if(typeof arr[i] === 'number'){
result += (level * arr[i]);
} else if(Array.isArray(arr[i])){
result += findWeightedSum(arr[i], level + 1);
}
}
return result;
};
console.log(findWeightedSum(arr));
46
How It Works
The function works recursively:
- It iterates through each element in the array
- If an element is a number, it multiplies it by the current level and adds to the result
- If an element is an array, it recursively calls the function with increased level
- Returns the total weighted sum
Alternative Example
Let's test with a different nested array:
const arr2 = [1, [2, [3, 4]], 5];
console.log("Array:", JSON.stringify(arr2));
console.log("Weighted sum:", findWeightedSum(arr2));
// Calculation: (1 * 1) + (2 * 2) + (3 * 3) + (4 * 3) + (5 * 1)
// = 1 + 4 + 9 + 12 + 5 = 31
Array: [1,[2,[3,4]],5] Weighted sum: 31
Conclusion
The weighted sum of a nested array is calculated by multiplying each element with its nesting level. This recursive approach efficiently handles arrays nested to any depth by incrementing the level parameter with each recursive call.
