- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implementing partial sum over an array using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers. Our function should construct and return a new array in which each corresponding element is the sum of all the elements right to it (including it) in the input array.
Example
Following is the code −
const arr = [5, 6, 1, 3, 8, 11]; const partialSum = (arr = []) => { let sum = arr.reduce((acc, val) => acc + val); const res = []; let x = 0; if(arr.length === 0){ return [0]; } for(let i = 0; i <= arr.length; i += 1) { res.push(sum); x = arr[i]; sum -= x; }; return res; }; console.log(partialSum(arr));
Output
[ 34, 29, 23, 22, 19, 11, 0 ]
Advertisements