I have an array like this:
var array = [0, 4, 6, 6, 6, 6, 6, 6];
I want a function to find the sum of the arrays values up to a certain index.
e.g. up to index 4 will be 0 + 4 + 6 + 6 + 6 = 22
Here's what I have so far:
var array = [0, 4, 6, 6, 6, 6, 6, 6];
const index = 4;
function sumUpToIndex(array, index) {
var result = 0;
for(i = 0; i < index; i++) {
result += array[i];
}
return result;
}
console.log(sumUpToIndex(array, index));
e.g. up to index 4 will be 0 + 4 + 6 + 6 + 6 = 22
Is a little mistake. you mean a) 4 = 16 or 5 = 22
working example where you can check
const i = document.querySelector('input')
i.addEventListener('keyup', (e) => {
const to = e.target.value;
const array = [0, 4, 6, 6, 6, 6, 6, 6].slice(0, to);
const sum = array.reduce((accumulator, a) => {
return accumulator + a;
}, 0);
console.log(sum);
})
<input type="number">