I am trying to find the index of an object in an array that contains a timestamp that matches the current date. Today is the 27th, so based off of my dataset, it should return the first index. I have tried two solutions, neither of which work for different reasons. I am open to using a solution to either method.
I have tried using an exact string match.
const index = _.findIndex(data, function(day) {
return day.timestampUtc === moment().startOf('day').toISOString() })
The above does not work because it is trying to match 2021-01-27T00:00:00Z
to 2021-01-27T06:00:00.000Z
which never catches because it would return undefined.
I have also tried
const index = _.findIndex(data, function(day) {
return moment(day.timestampUtc).day() === moment().day() }) //should return 1, but returns 2
This one didn't work because using moment(day.timestampUtc)
would evaluate it to the day before due to timezone offset, so my returned index would be one too high because it evaluates against one day early.
data
[{
timestampUtc: "2021-01-26T00:00:00Z"
weatherCodeType: "FLURRIES"
},
{
timestampUtc: "2021-01-27T00:00:00Z"
weatherCodeType: "RAIN"
}, //I want this one
{
timestampUtc: "2021-01-28T00:00:00Z"
weatherCodeType: "SNOW"
},
]
question from:
https://stackoverflow.com/questions/65926686/using-moment-js-to-find-the-index-of-an-object-matching-todays-date 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…