Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading