Will .map() with an if-condition loop over all indexes in an array? | JS React

I have an array called temperatures with data from an API call. I want to render part of the data only when certain conditions are met, and the code I have tried to achieve this with can be seen below:

tLowNext1Day =  { 
   temperatures.map((temperature, index ) => { 
       if( temperature.time[index] === todaysDate(0)) 
         return (
            <span key={index}>{
              temperature.data.instant.details.air_temperature+'°'}
             </span>
           )}

What I think this code will do is look at the data in all the indexes and render the data only when the condition is met (in this case it is whether the date in the data is today’s date), however, nothing gets rendered.

If my thinking is wrong here (which it seems), what would be a better way to solve the following problem:

  • While in the JSX, look at the date in each index in the array, temperatures.
  • Render the temperature when the time at the index matches the date of interest.

Thanks!

Answer

temperature inside your loop is already equal to temperatures[index] so you don’t need to do `temperature[index] anymore.

And even though you are doing temperature.time[index] which doesn’t make sense to put that index to your time variable.

So your code would need to be:

tLowNext1Day =  
   temperatures.map((temperature, index ) => { 
         return (
            <span key={index}>{
              temperature.time === todaysDate(0) ? 
              temperature.data.instant.details.air_temperature+'°' : ""
             }
             </span>
           )
    }

Or even better to be:

tLowNext1Day =  
   temperatures.map((temperature, index ) => {
         if(temperature.time === todaysDate(0))
            return (
               <span key={index}>
               {temperature.data.instant.details.air_temperature+'°'}
               </span>
            )
         return null;
    }
  • One more note is that you should not use your looping index as rendering keys. That will mess up with React rendering in some cases