I’ve been stuck on this too long. I’m trying to filter countList for all primes, but I’m not having any luck. I’m just having trouble finding the primes. I will write the condition that I want to pass:
The number is greater than 1 AND none of the divisors can divide the number without a remainder.
function sumPrimes(num) {
var countList = (function numberList(integer) {
var array = [];
for (var i = 2; i <= integer; i++) {
array.push(i);
}
return array;
}(num));
return countList.filter(function(value) {
for (var i = 1; i < value;) {
return (value > 1) && (value % i === 0) ? value : false;
}
});
}
sumPrimes(10);
It looks like you have a good start with countList creating an array and pushing all the values from 2 up to and including num.
Let’s walkthrough what you’re trying to do with the filter method:
return countList.filter(function(value) { // filtering to return only the values that are true
for (var i = 1; i < value;) { // looping through from 1 to the element to see if it is a prime. does the 'i' actually ever change if there is no third expression in the for loop in which to increment/decrement i?
return (value > 1) && (value % i === 0) ? value : false; // this is saying return a true or false value right away to be in the new array or not
}
});
Things to think about:
the for loop doesn’t have a third expression to increment i, so i will always be 1 and all the values in the array will be returned.
is there a reason you need to start looping in the for loop with the number 1? any value modded by 1 will be 0 and that’s why the entire countList is returned.
decide when to return true or false. might you return either true false while the loop is still continuing to the next i value in the for loop or maybe returning something when the loop is over or a combination of both?