2

I'm working on a challenge where I need to check what numbers of array are even, odd and prime. Then they need to be assigned different color each. What I came up with so far:

const Grid = () => {
  const arr = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
  
  return (
    <div className='grid'>
      {arr.map(number=><span key={number}
        style={
         number% 2 ===0 ? {backgroundColor:'green'}   :
        (number% 2 !==0 ? {backgroundColor: 'yellow'} : {backgroundColor:'red'})
       }>{number}</span>)}
  </div>
  );
}

ReactDOM.render(<Grid />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

But it does not really check if number is prime. Is there a way of doing that using ternary operator?

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
Al_Milligan
  • 119
  • 1
  • 2
  • 12
  • 3
    You'd have to make you own prime number checking function that returns a boolean. If it returns a boolean, you can continue using the ternary operator – Samathingamajig Oct 27 '20 at 14:27
  • 1
    Determining whether a number is prime is generally thought to have no (100% accurate) closed-form solution. You have to use something like a sieve of Eratosthenes to find primes. In your case, you could simply "know" the primes less than 20 of course. – Pointy Oct 27 '20 at 14:28
  • 3
    Unrelated suggestion: don't add inline styles, add semantic CSS classnames such as "odd/even/prime" Now you can easily mark an item as both prime and odd (or even) through CSS styles – Ruan Mendes Oct 27 '20 at 14:28
  • 1
    The [Sieve of Eratosthenes](https://www.geeksforgeeks.org/sieve-of-eratosthenes/) can help you find all the prime numbers up to a certain point. https://stackoverflow.com/questions/44691934/how-to-find-if-a-number-is-breakable-into-exactly-2-prime-factors – Samathingamajig Oct 27 '20 at 14:30
  • 2
    Here's an example of finding whether a number is prime https://stackoverflow.com/questions/40200089/number-prime-test-in-javascript Please rework your question showing some attempt at testing if a number is prime. – Ruan Mendes Oct 27 '20 at 14:31

0 Answers0