Prime numbers code logic

I have to change the logic of my prime numbers code. Right Now I don’t wanna use the filter and arrow method in my code. How can I do that?
Here’s my code :let number = [1, 8, 7, 3, 2, 9, 10, 12];

number = number.filter((myArray) => {
for (let i = 2; i <= Math.sqrt(myArray); i++) {
if (myArray % i === 0) {
return false;
}
return true;
}
});
console.log(number);

First, your function doesn’t work correctly at the moment, because you are returning true within the for loop.

Second, if you don’t want to use .filter, why did you choose to use .filter in the first place? Unless you clarify, I’m assuming that this is some code snippet you copied from elsewhere, but you’re not comfortable with the methods and syntax and now want to change it to something simpler.

Remember that .filter is an array method that technically does the same as a for loop:

  • it loops over the array
  • pushes all the numbers that pass the “prime” test into a new array
  • finally returns that new array

With that list given, you should be able to rewrite the code so that it uses a for loop instead of .filter (you’ll have two for loops then, an outer an an inner loop).

@jsdisco thanks for the detailed answer but I only wanna know that substitute of arrow function.

The variable you’ve called myArray is a number, not an array, that’s super confusing. But anyway

(someValue) => {
  return // do some stuff
}
function (someValue) {
  return // do some stuff
}

Yeah, plus the variable number is actually an array :sweat_smile:

Sorry @naimiii not trying to make fun of you. @DanCouper already showed the pattern for how to replace an arrow function with a regular function, but get back if you’re still struggling to apply that to your code.

3 Likes

@jsdisco I have made the logic by following @DanCouper comment.
here’s my logic using regular function

function checkPrime(number) {
  if (number <= 1) {
    return false;
  } else {
    for (let i = 2; i < number; i++) {
      if (number % i == 0) {
        return false;
      }
    }
    return true;
  }
}
console.log(checkPrime(10));

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

You only need to go up to the square root of number (so i <= Math.sqrt(number);) in the loop.

You can also return false before the loop if the number is an even number that isn’t 2. Then you can start the loop at 3 and increment by 2

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.