
- 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
Converting array of Numbers to cumulative sum array in JavaScript
We have an array of numbers like this −
const arr = [1, 1, 5, 2, -4, 6, 10];
We are required to write a function that returns a new array, of the same size but with each element being the sum of all elements until that point.
Therefore, the output should look like −
const output = [1, 2, 7, 9, 5, 11, 21];
Therefore, let’s write the function partialSum(),
The full code for this function will be −
const arr = [1, 1, 5, 2, -4, 6, 10]; const partialSum = (arr) => { const output = []; arr.forEach((num, index) => { if(index === 0){ output[index] = num; }else{ output[index] = num + output[index - 1]; } }); return output; }; console.log(partialSum(arr));
Here, we iterated over the array and kept assigning the elements of output array a new value every time, the value being the sum of current number and its predecessor.
The output of the code in the console will be −
[ 1, 2, 7, 9, 5, 11, 21 ]
- Related Articles
- Converting array to set in JavaScript
- Retaining array elements greater than cumulative sum using reduce() in JavaScript
- How to Find a Cumulative Sum Array in Java?
- Converting string to an array in JavaScript
- Converting array of objects to an object in JavaScript
- Sum of all prime numbers in an array - JavaScript
- Converting multi-dimensional array to string in JavaScript
- Converting object to 2-D array in JavaScript
- Converting array to phone number string in JavaScript
- Converting a JavaScript object to an array of values - JavaScript
- Taking the absolute sum of Array of Numbers in JavaScript
- Converting array into increasing sequence in JavaScript
- Converting array of objects to an object of objects in JavaScript
- Cumulative sum of elements in JavaScript
- Non-composite numbers sum in an array in JavaScript

Advertisements