
- 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
Partial sum in array of arrays JavaScript
We are required to write a JavaScript function that takes in an array of arrays of numbers. For each subarray, the function such create a partial sum subarray (an array in which a particular value is the sum of itself and the previous value).
For example −
If the input array is −
const arr = [ [1, 1, 1, -1], [1, -1, -1], [1, 1] ];
Then the output should be −
const output = [ [1, 2, 3, 2], [1, 0, -1], [1, 2] ];
Example
const arr = [ [1, 1, 1, -1], [1, -1, -1], [1, 1] ] const partialSum = (arr = []) => { const res = [] arr.forEach(sub => { let accu = 0 const nestedArr = [] sub.forEach(n => { accu += n; nestedArr.push(accu); }); res.push(nestedArr); }); return res; }; console.log(partialSum(arr));
Output
And the output in the console will be −
[ [ 1, 2, 3, 2 ], [ 1, 0, -1 ], [ 1, 2 ] ]
- Related Articles
- Implementing partial sum over an array using JavaScript
- Reverse sum of two arrays in JavaScript
- How to create an array of partial objects from another array in JavaScript?
- Array of objects to array of arrays in JavaScript
- How to sum elements at the same index in array of arrays into a single array? JavaScript
- Sum arrays repeated value - JavaScript
- Sum JavaScript arrays repeated value
- Multiply and Sum Two Arrays in JavaScript
- Column sum of elements of 2-D arrays in JavaScript
- Get the smallest array from an array of arrays in JavaScript
- How to filter out common array in array of arrays in JavaScript
- Converting array of arrays into an object in JavaScript
- Extract arrays separately from array of Objects in JavaScript
- Split Array of items into N Arrays in JavaScript
- Turning a 2D array into a sparse array of arrays in JavaScript

Advertisements