const arr = [4, 7, 6, 1, 2, 8];
const range = 5;
let sum = 0;
function sumUpToRange(arr, range) {
if(range > arr.length) {
range = arr.length;
}
for(let i = 0; i < range; i++) {
sum +=arr[i];
}
return sum;
}
console.log(sumUpToRange(arr, range));
Output:
20
- From the above program we need to ensure that the range should not exceed the length of the array. If it is exceeding we will assign the range to the array length.
- Given range is 5. So the sum of first five elements should calculate as 4 + 7 + 6 + 1 + 2 which is equal to 20.
We can also write this program by using slice and reduce methods as follows
const arr = [4, 7, 6, 1, 2, 8];
const range = 5;
function sumUpToRange(arr, range) {
return arr.slice(0, range).reduce((acc, num) => acc + num, 0)
}
console.log(sumUpToRange(arr, range));
- Here arr.slice(0, range) extracts the elements from 0 to 5. i.e, [4, 7, 6, 1, 2];
- reduce method starts with an initial value of
0and adds each number to the accumulator and returns 20 as the output.