Sum All Primes Filter Problem


I’ve been stuck on Sum All Primes for ages, probably spent a good 4 hours trying different solutions.

I thought I was getting somewhere using filter, though it seems to be going wrong, as I get a console error of “Reduce of empty array with no initial value” so for some reason I assume this means the filter isn’t working.

Can anyone point me in the correct direction of what I am doing wrong? I’m not looking for the answer per se, just want to know what I am doing wrong…or if I am barking up the wrong tree completely.

Code below - thanks, James

function sumPrimes(num) {
var array = [];
for (var i=2; i<=num; i++) {
array.filter(function() {
for (var j=0; j<=array.length; j++) {
if (num % array[j] === 0) {
return false;

  return true;

}).reduce(function(a,b) {
return a + b;


array.filter … this filters the array so there is no need for your for loop which wont work

array.filter(function(x) { // add something eg x … to your code here

what is the x you ask … picture filter as looping through your array handing you out one item at a time … so we call it x … good as any other name … so in the function we are given this x which is a entry from your array … so there is no need for you to write a for loop looping through your array to get this
all you need to do is

return true;
} else {
return false

you will then find your reduce part works 

but unfortunately formula gives wrong result as you are not getting prime numbers in your array
all primes up to 10 are 2,3,5,7,
here is your code with my changes so you can look and step through each line and see what is going on
1 Like