![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
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){ const res = []; if(start > end){ return res; }; for(let i = start; i <= end; i++){ res.push(this[i]); }; return res; }; Array.prototype.sumRange = sumRange; console.log(arr.sumRange(0, 4));
Output
And the output in the console will be −
[ 1, 2, 3, 4, 5 ]
Advertisements