0

Working on a TV timetable thing... I have an array of objects with dates as properties, like this:

let episodes = [
{"episodeName":"Welcome to the Hellmouth","episodeDate": new Date(1997, 2, 10)},
{"episodeName":"The Harvest","episodeDate": new Date(1997, 2, 10)},
{"episodeName":"Witch","episodeDate": new Date(1997, 2, 17)}]

For some reason, if I try to use a function, it doesn't seem to register any episodeDate as the same as another Date -- it basically just functions as a string.

var testDate = new Date(1997, 2, 10);
let test = episodes.find(test => test.episodeDate === testDate);
console.log(test);

This returns undefined. But if I search using episodeName, for example, in the same function, it works.

My desire is for user input to enter a date and I show what episode aired nearest that date. I've looked at tutorials and understand how to calculate nearest date from an array, but I don't understand how to do that while the date is in an object in an array-- should I convert it? Should I make it into a string?

I'm pretty new to JS.

  • 1
    `Date`s are objects(passed by reference), you shouldn't compare them like primitives, either stringify them, or use some library to help with dates i.e. `date-fns` – Eggy Jun 23 '21 at 14:38
  • Ok, thanks! So if I stringify it, will I be able to calculate the nearest date to user input? Every example I've seen for finding the nearest date also uses date objects... so I'd have to convert it to a string and then convert it back to a date? –  Jun 23 '21 at 14:40
  • Possible duplicate of [JavaScript Date Object Comparison](https://stackoverflow.com/questions/7606798/javascript-date-object-comparison). – SuperStar518 Jun 23 '21 at 14:42
  • To test for equality you need to convert to a primitive, so either string or number will do the job. If the time value of the Date objects is set to midnight at the start of the day, then `+date1 == +date2` will return true if they are the same day as unary + converts the operand to number, so is equivalent to `date1.getTime() == date2.getTime()`, but less to type. :-) – RobG Jun 24 '21 at 03:02

0 Answers0