

- 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
Accumulating array elements to form new array in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers, arr, as the first argument and a number, num, (num <= length of array) as the second argument
Our function should add up each contiguous subarray of length num of the array arr to form corresponding elements of new array and finally return that new array
For example, if the input to the function is −
const arr = [1, 2, 3, 4, 5, 6]; const num = 2;
Then the output should be−
const output = [3, 5, 7, 9, 11];
Output Explanation
Because 1 + 2 = 3, 2 + 3 = 5, and so on...
Example
Following is the code−
const arr = [1, 2, 3, 4, 5, 6]; const num = 2; const accumulateArray = (arr = [], num = 1) => { const res = []; let sum = 0, right = 0, left = 0; for(; right < num; right++){ sum += arr[right]; }; res.push(sum); while(right < arr.length){ sum -= arr[left]; sum += arr[right]; right++; left++; res.push(sum); }; return res; }; console.log(accumulateArray(arr, num));
Output
Following is the console output−
[3, 5, 7, 9, 11]
- Related Questions & Answers
- How to add new array elements at the beginning of an array in JavaScript?
- Counting the occurrences of JavaScript array elements and put in a new 2d array
- Formatting JavaScript Object to new Array
- Can form target array from source array JavaScript
- JavaScript - Constructs a new array whose elements are the difference between consecutive elements of the input array
- Split array entries to form object in JavaScript
- Can array form consecutive sequence - JavaScript
- Sorting Array Elements in Javascript
- Rearranging array elements in JavaScript
- How to replace elements in array with elements of another array in JavaScript?
- C++ program to find array after inserting new elements where any two elements difference is in array
- Shift certain array elements to front of array - JavaScript
- Mapping an array to a new array with default values in JavaScript
- Trim and split string to form array in JavaScript
- Compare array elements to equality - JavaScript
Advertisements