-1

Good morning, am getting stuck with this kata, anyone can explain me ? In this kata i have to return the sum of elements occupying prime-numbered indices. I started my code like that, but didn't know what to do next. THANK YOU in advance.

function total(arr) {
  for (let i = 2; i < arr.length; i++) {}
};
Shinichi
  • 13
  • 1
  • 8

1 Answers1

1
  1. Please use ; after breaking condition which is i < arr.length here for (let i = 2; i < arr.length, i++) {}

  2. You can loop over arr the way you are doing here and validate if index at which you are looping is prime itself.

  3. If 2nd step is met you can add the value into summation var sum

  4. return sum.

Please follow this thread to find know more about calculating if value is prime. Number prime test in JavaScript

function isPrime(num) {
  for(var i = 2; i < num; i++)
    if(num % i === 0) return false;
  return num > 1;
}

function total(arr) {
  var sum = 0;
  for (let i = 2; i < arr.length; i++) {
    if(isPrime(i)) {
        sum = sum + arr[i]
    }
  }
  return sum;
}
Gurwinder
  • 509
  • 2
  • 11