Skip to content

Instantly share code, notes, and snippets.

@Korveld
Created April 15, 2024 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Korveld/3de5f0c783de41ff9226216ab6834938 to your computer and use it in GitHub Desktop.
Save Korveld/3de5f0c783de41ff9226216ab6834938 to your computer and use it in GitHub Desktop.
Sort and filter an array of objects by date range
// Define the array of objects
const data = [
{ id: 1, date: '2023-05-15' },
{ id: 2, date: '2023-05-10' },
{ id: 3, date: '2023-05-20' },
// Add more objects as needed
];
// Function to sort and filter the array by date range
function sortAndFilterByDateRange(array, startDate, endDate) {
// Sort the array by date
array.sort((a, b) => new Date(a.date) - new Date(b.date));
// Filter the array to get only the objects within the date range
const filteredArray = array.filter(item => {
const date = new Date(item.date);
return date >= startDate && date <= endDate;
});
return filteredArray;
}
// Example: Sort and filter by date range from '2023-05-10' to '2023-05-15'
const startDate = new Date('2023-05-10');
const endDate = new Date('2023-05-15');
const result = sortAndFilterByDateRange(data, startDate, endDate);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment