firstIndex - Hashimoto-Noriaki/react-calendar GitHub Wiki

コード

 const scheduleList = getScheduleList()
    scheduleList.forEach((schedule) => {
      const firstIndex = newDateList.findIndex((oneWeek) =>
        oneWeek.some((item) => isSameDay(item.date, schedule.date))
      )
      if (firstIndex === -1) return;
      const secondIndex = newDateList[firstIndex].findIndex((item) =>
        isSameDay(item.date, schedule.date)
      )

      newDateList[firstIndex][secondIndex].schedules = [
        ...newDateList[firstIndex][secondIndex].schedules,
        schedule,
      ]
    })

    setDateList(newDateList)

🔸 分解して詳しく説明

const scheduleList = getScheduleList()

scheduleListは全てのスケジュール(Schedule[])を取得する

scheduleList.forEach((schedule) => {
  ...
})
  • 各スケジュールに対してループ
  • 1件ずつschedule.dateを使って、該当する日付を探す
const firstIndex = newDateList.findIndex((oneWeek) =>
  oneWeek.some((item) => isSameDay(item.date, schedule.date))
)

schedule.dateに一致する日付が***どの週(oneWeek[])***にあるかを探す 一致する週が見つかればfirstIndexにその週のインデックスを返す 見つからなければ-1

if (firstIndex === -1) return;
  • 見つからなかった場合はスキップ(そのスケジュールは無視)
const secondIndex = newDateList[firstIndex].findIndex((item) =>
  isSameDay(item.date, schedule.date)
)
  • その週の中で、スケジュールの日付と一致する「曜日(その週の何日目)」を探す
  • それが見つかれば、その日のインデックスを取得
newDateList[firstIndex][secondIndex].schedules = [
  ...newDateList[firstIndex][secondIndex].schedules,
  schedule,
]

該当日のschedules配列にscheduleを追加 ...スプレッド構文で、既存の予定を保ちつつ新しい予定を追加