- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Reduce an array to the sum of every nth element - JavaScript
We are required to write a JavaScript function that takes in an array of numbers and returns the cumulative sum of every number present at the index that is a multiple of n from the array.
Let’s write the code for this function −
const arr = [1, 4, 5, 3, 5, 6, 12, 5, 65, 3, 2, 65, 9]; const num = 2; const nthSum = (arr, num) => { let sum = 0; for(let i = 0; i < arr.length; i++){ if(i % num !== 0){ continue; }; sum += arr[i]; }; return sum; }; console.log(nthSum(arr, num));
Output
Following is the output in the console −
99
Above, we added every 2nd element beginning with index 0 i.e.
1+5+5+12+65+2+9 = 99
- Related Articles
- Finding sum of every nth element of array in JavaScript
- How to remove every Nth element from an array JavaScript?
- JavaScript: take every nth Element of Array and display a fixed number of values?
- Finding the nth power of array element present at nth index using JavaScript
- JavaScript reduce sum array with undefined values
- Reduce an array to groups in JavaScript
- Style every element that is the nth element of its parent with CSS
- Finding nth element of an increasing sequence using JavaScript
- Nth element of the Fibonacci series JavaScript
- Python – Extract Kth element of every Nth tuple in List
- Find maximum sum taking every Kth element in the array in C++
- Join every element of an array with a specific character using for loop in JavaScript
- Finding the nth missing number from an array JavaScript
- Nth smallest element in sorted 2-D array in JavaScript
- Retaining array elements greater than cumulative sum using reduce() in JavaScript

Advertisements