How to classify array numbers as even, odd and prime and assign them colors to style divs in Javascript?

Viewed 251

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?

0 Answers
Related