
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Recursion - Sum Nested Array in JavaScript
- Sum of nested object values in Array using JavaScript
- Nested List Weight Sum II in Python
- How to sum all elements in a nested array? JavaScript
- JavaScript recursive loop to sum all integers from nested array?
- Flattening a deeply nested array of literals in JavaScript
- Grouping nested array in JavaScript
- Product of numbers present in a nested array in JavaScript
- Simplifying nested array JavaScript
- Join in nested array in JavaScript
- Finding the maximum in a nested array - JavaScript
- Finding a greatest number in a nested array in JavaScript
- Remove item from a nested array by indices in JavaScript
- Convert nested array to string - JavaScript
- Transform nested array into normal array with JavaScript?

Advertisements