Home > Software design >  How to add sum of even INDICES in javascript?
How to add sum of even INDICES in javascript?

Time:10-08

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]))

CodePudding user response:

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]))

CodePudding user response:

Here is a version with .reduce():

const data=[1,2,3,4,5];

console.log(data.reduce((a,c,i)=>
 a (i%2?0:c)))

  • Related