I have the following two arrays:
const dates = [ "January 1st, 2022", "January 2nd, 2022", More dates...]
const events = [
{
id: 1,
date: "January 10th, 2022",
title: "Have a meeting",
}
More events...
]
What I would like to do is map through the dates array, displaying all dates and also map through the events array and display the event.title when the event.date matches the corresponding date in the date array.. How can I map the events array with the dates array and when the dates match output the event.title?
Currently I have this:
{dates.map((date, i) => (
<li
key={i}
>
{date}
//Here I would also like to display the {event.title} when the dates match.
</li>
))}
If all your dates are strings and they match the strings in the dates array, then you could structure your events as an object where the keys are the dates. (This is assuming there are no overlapping events).
The benefit of this method is that it you only have two loops which makes the code very performant.
const structuredEvents = events.reduce((acc, cur => {
acc[cur.date] = cur;
return acc;
}, {});
In your loop select the event based on the date.
{dates.map((date, i) => {
const event = structuredEvents[date];
return (
<li
key={i}
>
{date}
{event?.title}
</li>
);
})}
(with Optional chaining operator (?.))
{dates.map((date, i) => (
<li
key={i}
>
{events.find(e => e.date == date)?.title}
</li>
))}
import logo from './logo.svg';
import './App.css';
const dates = [ "January 1st, 2022", "January 2nd, 2022", ]
const events = [
{
id: 1,
date: "January 1st, 2022",
title: "Have a meeting",
},
{
id: 1,
date: "January 2nd, 2022",
title: "second meeting",
},
{
id: 1,
date: "January 3rd, 2022",
title: "Have a meeting",
}
]
function App() {
return (
<div className="App">
{dates.map((date, i) => (
<li
key={i}
>
{events.map((data,i)=> {
console.log(data,date,"data...")
return (
<div>
{data.date == date ?
<div>Here I would also like to display the {data.title} when the dates match.</div>
:null}
</div>
)})}
</li>
))}
</div>
);
}
export default App;