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 a range in an array JavaScript
We are required to write an Array function (functions that lives on Array.prototype object). The function should take in a start index and an end index and it should sum all the elements from start index to end index in the array (including both start and end).
Example
const arr = [1, 2, 3, 4, 5, 6, 7];
const sumRange = function(start = 0, end = 1){
let sum = 0;
if(start > end){
return sum;
}
for(let i = start; i <= end; i++){
sum += this[i];
}
return sum;
};
Array.prototype.sumRange = sumRange;
console.log(arr.sumRange(0, 4));
Output
15
How It Works
The function iterates from the start index to the end index (inclusive) and accumulates the sum of all elements in that range. If the start index is greater than the end index, it returns 0.
Alternative Examples
const numbers = [10, 20, 30, 40, 50]; console.log(numbers.sumRange(1, 3)); // Sum of 20 + 30 + 40 console.log(numbers.sumRange(0, 2)); // Sum of 10 + 20 + 30 console.log(numbers.sumRange(2, 1)); // Invalid range, returns 0
90 60 0
Conclusion
The sumRange prototype method provides a convenient way to calculate the sum of array elements within a specific range. It handles edge cases like invalid ranges and uses default parameters for flexibility.
Advertisements
