Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding sum of every nth element of array in 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.
Understanding the Problem
When we say "every nth element", we mean elements at indices 0, n, 2n, 3n, and so on. For example, if n=3, we sum elements at indices 0, 3, 6, 9, etc.
Example
Let's find the sum of every 3rd element from an array:
const arr = [5, 3, 5, 6, 12, 5, 65, 3, 2];
const num = 3;
const nthSum = (arr, num) => {
let sum = 0;
for(let i = 0; i
76
Elements at indices 0, 3, 6: 5 6 65
Sum: 76
Alternative Approach Using Step Increment
Instead of checking every index, we can increment by n directly:
const nthSumOptimized = (arr, n) => {
let sum = 0;
for(let i = 0; i
76
82
Using Array Methods
A more functional approach using reduce():
const nthSumFunctional = (arr, n) => {
return arr.reduce((sum, value, index) => {
return index % n === 0 ? sum + value : sum;
}, 0);
};
const arr = [5, 3, 5, 6, 12, 5, 65, 3, 2];
console.log(nthSumFunctional(arr, 3));
76
Comparison of Methods
| Method | Performance | Readability | Use Case |
|---|---|---|---|
| For loop with continue | Good | Clear | General purpose |
| For loop with step increment | Best | Very clear | When n is known and constant |
| Reduce method | Good | Functional style | Functional programming preference |
Conclusion
The step increment approach (i += n) is most efficient as it skips unnecessary iterations. Choose the method that best fits your coding style and performance requirements.
Advertisements
