Reputation: 19
Here is the code I'm using to go through an array and pick out the prime numbers and push them to an empty array. My problem is that when I node this, it's only returning the first prime number the code finds in the array regardless if there are more prime numbers in the array. I can't spot what I might be missing...
let primeXray = function(num) {
if (num < 2)
return false;
for (i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
let choosePrimes = function(nums) {
let primeBlock = [];
for (i = 0; i < nums.length; i++) {
let num = nums[i];
if (primeXray(num)) {
primeBlock.push(num);
}
}
return primeBlock;
}
console.log(choosePrimes([36, 48, 9, 13, 19])); // [ 13, 19 ]
console.log(choosePrimes([5, 6, 4, 11, 2017])); // [ 5, 11, 2017 ]
Upvotes: 0
Views: 115
Reputation: 76925
The problem is that you do not declare i
with let
or var
, so it's created by JS and reused. Your primeXray
changes i
which disturbs the other function
let primeXray = function(num) {
if (num < 2)
return false;
for (let i = 2; i < num; i++) {
if (num % i === 0)
return false;
}
return true;
}
let choosePrimes = function(nums) {
let primeBlock = [];
for (let i = 0; i < nums.length; i++) {
let num = nums[i];
if (primeXray(num))
primeBlock.push(num);
}
return primeBlock;
}
Upvotes: 1