1
1
12332112020-04-30 19:45:04
JavaScript
1233211, 2020-04-30 19:45:04

How to take an object from an array?

There is an array with objects, objects have a "date" field, how to take an object from the array, in which the "date" field == today's date, or (if there is no data for the current date) the nearest previous date?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-04-30
@1233211

const timestamp = (year, month = 1, day = 1) => new Date(year, month - 1, day).getTime();

const entries = [
  {
    type: 'error',
    date: timestamp(2020, 4, 30)
  },
  {
    type: 'log',
    date: timestamp(2020, 4, 29)
  },
  {
    type: 'info',
    date: timestamp(2020, 4, 25)
  }
];

const date = new Date();
const today = timestamp(date.getFullYear(), date.getMonth() + 1, date.getDate());
const interval = 24 * 60 * 60 * 1000;

const entry = entries.find(entry => (entry.date >= today && entry.date <= today + interval));

console.log(entry); // { type: 'error', date: 1588183200000 }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question