skip to Main Content

I am wondering, from the research I have done I have not found anything, but is there a way to conditionally map through an array of objects. For instance, I have an array of objects for doctors appointments and I am only wanting to map through the doctors appointments where the date has not past.

I normally do this, but this is not adding in any conditions.

{doctorsApptData.map(apptData => (
   <div>This date is valid! {apptData.date}</div>
))}

I have tried something like this, but no luck

{doctorsApptData.map(apptData => (
apptData.date >= DateTime.now() && (
   <div>This date is valid! {apptData.date}</div>
)))}

Thanks!

2

Answers


  1. You can use filter method before map. This method creates a new array with only the elements that meet a certain condition.

    For example:

    {
      doctorsApptData
        .filter((apptData) => apptData.date >= DateTime.now())
        .map((apptData) => <div>This date is valid! {apptData.date}</div>);
    }
    
    Login or Signup to reply.
  2. Yeah sure, so there are a few ways. What’s important is for us to correctly understand how passing in callbacks works in the context of higher order functions, since sorting functions like sort, map, filter etc are extremely commonly used.

    map() works like this:

    array.map((current, index) => {
        // whatever logic you want here
        return (???)
        }
    

    So in this case you could do something like

    doctorsApptData.map((apptData, index) => {
        if (apptData.date >= DateTime.now()){
            return(
                <div>This date is valid! {apptData.date}</div>
            )
        }
    )
    

    or if you really wanted to use a ternary (personally I’d be a little wary against using them too sparsely since they tend to compromise code readability):

    doctorsApptData.map((apptData, index) => {
        return(
            apptData.date >= DateTime.now && (<div>This date is valid! {apptData.date}</div>)
            )
        }
    )
    

    hope it helped!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search