
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Cumulative sum of elements in JavaScript
Suppose, we have an array of numbers like this −
const arr = [1, 2, 3, 4, 5, 6];
We are required to write a JavaScript function that takes in one such array and returns a new array with corresponding elements of the array being the sum of all the elements upto that point from the original array.
Therefore, for the above array, the output should be −
const output = [1, 3, 6, 10, 15, 21];
Example
The code for this will be −
const arr = [1, 2, 3, 4, 5, 6]; const findCumulativeSum = arr => { const creds = arr.reduce((acc, val) => { let { sum, res } = acc; sum += val; res.push(sum); return { sum, res }; }, { sum: 0, res: [] }); return creds.res; }; console.log(findCumulativeSum(arr));
Output
The output in the console −
[ 1, 3, 6, 10, 15, 21 ]
- Related Questions & Answers
- Cumulative average of pair of elements in JavaScript
- Retaining array elements greater than cumulative sum using reduce() in JavaScript
- Cumulative sum at each index in JavaScript
- Converting array of Numbers to cumulative sum array in JavaScript
- Return the cumulative sum of array elements treating NaNs as zero in Python
- Absolute sum of array elements - JavaScript
- Thrice sum of elements of array - JavaScript
- Return the cumulative sum of array elements over given axis treating NaNs as zero in Python
- Python program to find Cumulative sum of a list
- Dynamic Programming - Part sum of elements JavaScript
- Sum of distinct elements of an array - JavaScript
- Finding sum of all unique elements in JavaScript
- Sum of distinct elements of an array in JavaScript
- Return the cumulative sum of array elements over given axis 0 treating NaNs as zero in Python
- Return the cumulative sum of array elements over given axis 1 treating NaNs as zero in Python
Advertisements