Created
April 15, 2024 14:42
-
-
Save Korveld/3de5f0c783de41ff9226216ab6834938 to your computer and use it in GitHub Desktop.
Sort and filter an array of objects by date range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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