Sum All Primes (can't find my mistakes)

Tell us what’s happening:
Hello, I can’t seem to understand what’s wrong with this code.

sumPrimes(10) returns the correct result but everything further than that doesn’t work

Your code so far

function sumPrimes(num) {
  var primeSum =0;
  var sqrtI = 0;
  var primeArray = [];
  function add(a,b){
    return a+b;
  }
 
  for (i=2;i<=num;i++){
    primeArray.push(i);
    sqrtI = Math.sqrt(i);
   
    for (k=2;k<=sqrtI;k++){
      if (i % k === 0){
        
       primeArray.pop(i);
      }
    }
    
    
  
  }
    
  
 return primeArray.reduce(add,0);
}

sumPrimes(20);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/sum-all-primes

I think you may be confused about the pop function. What exactly do you think the following line does?

primeArray.pop(i);

You’re right, i realized that .pop() only removes whatever element is a the end of the array.

So i rewrote the code using .splice() and looping through the array backwards with and it all worked out.

function sumPrimes(num) {
var primeSum =0;
var sqrtI = 0;
var primeArray = [];
var testArray = [];
function add(a,b){
return a+b;
}

for (k=2;k<=num;k++){
primeArray.push(k);
}

for (i=primeArray.length-1;i>=0;i–){
sqrtI = Math.sqrt(primeArray[i]);

for (j=2;j<=sqrtI;j++){

    if (primeArray[i] % j===0){
    primeArray.splice(i,1);
}

}

}

return primeArray.reduce(add,0);
}

sumPrimes(977);