Home > Enterprise >  How to filter items from an array of day values where a day's integer value has to match any ti
How to filter items from an array of day values where a day's integer value has to match any ti

Time:02-22

In JSX I am mapping through a number of days that I have calculated in a month:

  {range(daysInMonth).map((i) => (
          <div
            className="day-cell day-cell--in-month"
            key={i}
          >
            {i   1}
          </div>
        ))}

I then have a array of events coming from an api:

const events = [
{
date: timestamp,
description: "Meeting with friends"
}
//More events//
]

How can I map through the array of events and match the event timestamp to the current timestamp of the date for the daysInMonth that is being mapped and then display the event description?

CodePudding user response:

In case the above comment's assumption ...

"the daysInMonth is just a number, for example for Feb it would be 28." ... thus, one can assume the timestamp/date value of an events item is an integer as well?

... applies, one could implement the preceding filter task in collaboration with some.

const events = [{
  date: timestamp,
  description: "Meeting with friends"
}/*, { More events }*/];


{
  range(
    
    daysInMonth
    
  ).filter(dayValue =>
    
    events.some(({ date }) => date === dayValue)
    
  ).map(dayValue => (
    <div
      className="day-cell day-cell--in-month"
      key={dayValue}
    >
      {dayValue   1}
    </div>
  ))
}

Edit

"... thus, one can assume the timestamp/date value of an events item is an integer as well?" – Peter Seliger

"... it's a timestamp from a MySQL database." – adherb

"... then within the already provided filter code of my answer one has to get the day from each events item's date value in order to make it comparable to the integer value of each daysInMonth item." – Peter Seliger

const events = [{
  date: timestamp,
  description: "Meeting with friends"
}/*, { More events }*/];


{
  range(

    daysInMonth

  ).filter(dayValue =>
    events.some(({ date }) =>
      new Date(date).getDay() === dayValue
    )
  ).map(dayValue => (
    <div
      className="day-cell day-cell--in-month"
      key={dayValue}
    >
      {dayValue   1}
    </div>
  ))
}
  • Related