

- 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 at each index in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers. The function constructs and return a new array that for a particular index, contains the sum of all the numbers up to that index.
For example −
If the input array is −
const arr = [1, 2, 3, 4, 5];
Then the output should be −
const output = [1, 3, 6, 10, 15];
We can use the Dynamic program to keep track of the sum in each iteration and just add the corresponding element to the sum to obtain the new element.
Example
Following is the code −
const arr = [1, 2, 3, 4, 5]; const cumulativeSum = arr => { let result = [arr[0]]; for(let i = 1; i < arr.length; i++) { result.push(arr[i] + result[i-1]); } return result; } console.log(cumulativeSum(arr));
Output
Following is the output on console −
[ 1, 3, 6, 10, 15 ]
- Related Questions & Answers
- Cumulative sum of elements in JavaScript
- Even index sum in JavaScript
- Converting array of Numbers to cumulative sum array in JavaScript
- How to find the cumulative sum for each row in an R data frame?
- Placing integers at correct index in JavaScript
- Retaining array elements greater than cumulative sum using reduce() in JavaScript
- Inserting element at falsy index in an array - JavaScript
- Reverse index value sum of array in JavaScript
- Greatest sum and smallest index difference in JavaScript
- Common element with least index sum in JavaScript
- How to sum elements at the same index in array of arrays into a single array? JavaScript
- How to create a Cumulative Sum Column in MySQL?
- Even numbers at even index and odd numbers at odd index in C++
- Subarray sum with at least two elements in JavaScript
- How to create a cumulative sum plot in base R?
Advertisements