
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Weight Sum of a Nested Array in JavaScript
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
Advertisements