Array Filter not filtering

DeSync :

I am trying to filter an array of random numbers to pull out primes.

I have a working function (isPrime) that appears to return true or false correctly but every number in the array is being "filtered" into the array returned by the filter.

I looked at the documentation for filter and watched some videos but I haven't figured it out, I think it may have to do with the function call inside of the filter. Can you tell me where my error is?

numArray = [];

for(i=0; i<1000; i++){
  numArray.push(Math.random(1000));
}

const isPrime = (num) => {
  for(i=2;i<num;i++){
    if(num % i === 0){
      return false;
    }
  }
  return true;
}

const results = numArray.filter(value => isPrime(value));
  
for(num in results){
  console.log(num);
  console.log(isPrime(num)) //added to demonstrate function is working and should return false to the filter                        
}

Maheer Ali :

You are generating random number in wrong way. Your code will only create an array of floating points less than 1 so according to your isPrime they all will be prime.

Note: Don't use variables without let or cosnt it can cause many problems in the code.

How to create random numbers?

  • Math.random() is function which returns a floating point number between 0 and 1.
  • You multiply that number with the max range you want to have.
  • After multiplying it will still be a floating number. So use Math.floor() to round the random float to an integer

let numArray = [];

for(let i=0; i<10; i++){
  numArray.push(Math.floor(Math.random() * 30));
}

const isPrime = (num) => {
  for(let i=2;i<num;i++){
    if(num % i === 0){
      return false;
    }
  }
  return true;
}

const results = numArray.filter(value => isPrime(value));

console.log(JSON.stringify(numArray))
console.log(JSON.stringify(results));

Answering OP's question that

"Why bottom for loop used to check the code gives numbers 5, 6 ... 997, 998"

In javascript arrays are basically objects. The for..in is a loop which iterates over the keys of the object not the values. So in case arrays keys are the indexes of the array which are 0...999 in above case. So it was logging those indexes

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=28317&siteId=1