0

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));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
CoderGuru
  • 29
  • 4
  • arrays are 0-indexed so either index 4 or 4 elements. In your example you are using the 0-indexed approach (5 elements). In the snippet you are using 4 elements approach. Take one or the other – Lelio Faieta Dec 20 '21 at 15:30
  • const sumUpToIndex = (arr, index) => arr.slice(0, index).reduce((s, a) => s + a, 0) – fingerpich Dec 20 '21 at 15:33

1 Answers1

0

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">
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79