FullStackJunkie
FullStackJunkie

Reputation: 19

Prime Checker function in javascript is only returning one prime number from an array containing multiple prime numbers

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

Answers (1)

Lajos Arpad
Lajos Arpad

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

Related Questions