Skip to content
Advertisement

How to add sum of even INDICES in javascript?

This is the official hw question.

Write a function named sum_even_index whose parameter is a list/array of decimal numbers. Your function must return the sum of entries at the parameter’s even indicies (e.g., the sum of the entries stored at index 0, index 2, index 4, and so on).

Ive been looking for hours and still cant figure it out. On this site most of the answers refer to the number in the array not the actual indice. This prints 0. But should print 4

function sum_even_index(x) {
  let sum = 0
  for (let i in x) {
    if (x.indexOf[i] % 2 === 0) {
      sum = sum + x[i];
    }

  }
  return sum;
}

console.log(sum_even_index([1, 2, 3, 4]))

Advertisement

Answer

If i understood you right you have to change this line if (x.indexOf[i] % 2 === 0) { to if (i % 2 === 0) {.

Update

ForEach loop

function sum_even_index(x){
  let sum = 0;
  
  x.forEach( (i, e) => {
    if (i % 2 === 0) {
      sum = sum + e;
    }
  })
  return sum;
}
console.log(sum_even_index([1,2,3,4]))

your approach but better you take the forEach loop

function sum_even_index(x){
  let sum=0;
  
  for (let i in x){
    if (i % 2 === 0) {
    sum = sum + x[i];
    }
    
  }
  return sum;
}
console.log(sum_even_index([1,2,3,4]))
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement