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
You can use
filter
method beforemap
. This method creates a new array with only the elements that meet a certain condition.For example:
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:
So in this case you could do something like
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):
hope it helped!