0

I'm currently making something that will first check if an element exists in an array, if it does exist already, it will remove it, else if not it will insert it. The element type here is a date, however, I seem to be having problems comparing it with itself.

Here is an example data set I'm using:

 const data = [
    {
      day: "Sun",
      index: 0,
      date: new Date(2099, 0, 4)
    },
    {
      day: "Mon",
      index: 1,
      date: new Date(2099, 0, 5)
    },
    {
      day: "Tue",
      index: 2,
      date: new Date(2099, 0, 6)
    }
]

Then, when a user click the button, here's the check:


  let [dates, setDates] = useState([]);

  const handleDayClick = (ind, day) => {
    const datesCpy = [...dates];
    let found = 0;
    for(let i = 0; i < datesCpy.length; i++) {
      console.log(`Comparing ${datesCpy[i]} to ${day}!`);
      if(datesCpy[i].toDateString() === day.toDateString()) {
        found = 1;
        datesCpy.splice(i, 1); //if already exists.. remove it.
        break;
      }
    }
    if(found === 0) {
      datesCpy.push(day);
    }
    ... //do other stuff here, irrelevant to question

I even get this in the console, which has identical values(but doesn't get into the if statement): Comparing Mon Jan 05 2099 00:00:00 GMT-0600 (Central Standard Time) to Mon Jan 05 2099 00:00:00 GMT-0600 (Central Standard Time)!

I have tried using indexOf and of course contains, but they never find the actual duplicate, so I resorted to using a c-style approach with a for loop and iterating. I also have tried comparing the actual date values rather than stringify-ing them, I had tried previous solutions from other SO questions, but they mentioned IndexOf, contains, etc. Is there something obvious I'm overlooking?

Dylan
  • 25
  • 3

0 Answers0