Rob Terrell
Rob Terrell

Reputation: 2562

Pair items in two separate arrays based on the date value

I currenty have an array of dates that looks like the following:

[
"2021-05-01",
"2021-05-02",
"2021-05-03",
]

In a separate entry array, I have entries that contain the dates that pertain to a specific date:

[
   {
      id: 5e24d1fa-aa66-4122-b1eb-97792f0893b0,
      name: "Rodriquez Family",
      selectedDates: ["2021-05-01"],
      status: "submitted"
    },
    {
      id: 269a0381-63c7-4ab6-92d8-7f7b836aee6f,
      name: "Test Family",
      selectedDates: ["2021-05-03"],
      status: "submitted"
    }
]

I am attempting to pair the two arrays for a result that would look something like the following:

 [
    {
      date: "2021-05-01",
      event: {
        id: 5e24d1fa-aa66-4122-b1eb-97792f0893b0,
        name: "Rodriquez Family",
        selectedDates: ["2021-05-01"],
        status: "submitted"
      }
    },
    {
      date: "2021-05-02",
      event: null
    },
    {
      date: "2021-05-03",
      event: {
        id: 269a0381-63c7-4ab6-92d8-7f7b836aee6f,
        name: "Test Family",
        selectedDates: ["2021-05-03"],
        status: "submitted"
      }
  ]

The issue I am running into is that as I loop through the events array and check if an event has a selected date that belongs to to a date in the dates array. It duplicates the dates for however many events there are. My function looks like the following:

const getDates = async () => {
      const addEvents = dateArr.map((date) => {
        return events.map((event) => {
          if (event.selectedDates.includes(date)) {
            return { date, event };
          }
          return { date, event: null, checked: false };
        });
      });
     console.log(addEvents.flat());
    };

I have included a condesandbox using react for debugging!! https://codesandbox.io/s/dawn-snow-03r59?file=/src/App.js The code sandbox will show how the dates are being duplicated.

Upvotes: 1

Views: 49

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28414

For each dateArr element, you're iterating over events and returning a list of objects with the two specified options. Instead, you can use Array#find to check if it exists or not:

const 
  dateArr = ["2021-05-01", "2021-05-02", "2021-05-03"],
  events = [
    { id: "5e24d1fa-aa66-4122-b1eb-97792f0893b0", name: "Rodriquez Family", selectedDates: ["2021-05-01"], status: "submitted" },
    { id: "269a0381-63c7-4ab6-92d8-7f7b836aee6f", name: "Test Family", selectedDates: ["2021-05-03"], status: "submitted" }
  ];

const list = dateArr.map(date => {
  const event = events.find(({ selectedDates = [] }) => selectedDates.includes(date));
  return event ? { date, event } : { date, event: null, checked: false };
});

console.log(list);

Upvotes: 1

Related Questions