Sara Ree
Sara Ree

Reputation: 3543

Check if dates in array contains a date later than the current date

I have an array of date object:

const dates = [
  '2021-11-01T19:49:08.678Z',
  '2021-11-01T20:13:27.954Z',
  '2021-08-31T19:15:16.452Z',
  '1983-04-16T20:18:39.802Z',
  '2022-02-02T20:26:14.992Z',
  '2022-02-02T20:30:36.374Z',
  '2022-02-02T20:33:09.266Z',
  '2022-02-02T20:35:34.615Z',
  '2022-02-02T20:44:19.131Z',
  '2022-02-02T20:48:17.274Z'
]

I want to check if at least one of the dates inside the array is later than the current date (if there is any date which has not reached yet return true, if all of them past return false)

Upvotes: 0

Views: 533

Answers (3)

Spectric
Spectric

Reputation: 31987

Use Array#some to parse each date and the > operator to check whether the date is later than the current date.

const arr = [
  '2021-11-01T19:49:08.678Z',
  '2021-11-01T20:13:27.954Z',
  '2021-08-31T19:15:16.452Z',
  '1983-04-16T20:18:39.802Z',
  '2022-02-02T20:26:14.992Z',
  '2022-02-02T20:30:36.374Z',
  '2022-02-02T20:33:09.266Z',
  '2022-02-02T20:35:34.615Z',
  '2022-02-02T20:44:19.131Z',
  '2022-02-02T20:48:17.274Z'
]

const hasPassed = arr.some(e => new Date(e) > new Date);
console.log(hasPassed);

Upvotes: 3

KooiInc
KooiInc

Reputation: 122906

Array.find should be sufficient for your problem I suppose

const referenceDate = new Date();
console.log([
  `2021-11-01T19:49:08.678Z`,
  `2021-11-01T20:13:27.954Z`,
  `2021-08-31T19:15:16.452Z`,
  `1983-04-16T20:18:39.802Z`,
  `2022-02-02T20:26:14.992Z`,
  `2022-02-02T20:30:36.374Z`,
  `2022-02-02T20:33:09.266Z`,
  `2022-02-02T20:35:34.615Z`,
  `2022-02-02T20:44:19.131Z`,
  `2022-02-02T20:48:17.274Z`
].find(d => new Date(d) > referenceDate)
)

Upvotes: 1

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

You can use Array.prototype.some for this:

const dates = [
    '2021-11-01T19:49:08.678Z',
    '2021-11-01T20:13:27.954Z',
    '2021-08-31T19:15:16.452Z',
    '1983-04-16T20:18:39.802Z',
    '2022-02-02T20:26:14.992Z',
    '2022-02-02T20:30:36.374Z',
    '2022-02-02T20:33:09.266Z',
    '2022-02-02T20:35:34.615Z',
    '2022-02-02T20:44:19.131Z',
    '2022-02-02T20:48:17.274Z',
];

// If they're strings
console.log(dates.some(d => new Date(d).valueOf() > Date.now()));

const asDates = dates.map(d => new Date(d));
// If they're actual Date objects
console.log(asDates.some(d => d.valueOf() > Date.now()));

const dates2 = [
    '1983-04-16T20:18:39.802Z',
];

console.log(dates2.some(d => new Date(d).valueOf() > Date.now()));

const asDates2 = dates2.map(d => new Date(d));
console.log(asDates2.some(d => d.valueOf() > Date.now()));

Upvotes: 1

Related Questions