filter date in javascript

To filter an array of dates in JavaScript, you can use the filter() method.

Assuming you have an array of date objects, you can filter them based on a specific range of dates.

For example, let's say you have an array of dates like this:

index.tsx
const dates = [
  new Date('2021-03-01'),
  new Date('2021-03-03'),
  new Date('2021-03-05'),
  new Date('2021-03-07'),
  new Date('2021-03-09')
];
148 chars
8 lines

You can filter the dates that fall between two specific dates like this:

index.tsx
const filteredDates = dates.filter(date => {
  const startDate = new Date('2021-03-02');
  const endDate = new Date('2021-03-08');
  return date >= startDate && date <= endDate;
});
182 chars
6 lines

This will return an array containing only the dates that fall between 2021-03-02 and 2021-03-08.

Note that the filter() method returns a new array containing the elements that pass the test. It does not modify the original array.

gistlibby LogSnag