Compare
Try in Playground →Sort, group, and analyze date arrays
Examples on this page are verified against the `ts-time-utils` v4.4.1 public exports.
Import
import { ... } from 'ts-time-utils/compare'; Examples
Sort & Filter
Sort dates and find min/max
import { sortDates, minDate, maxDate, closestDate } from 'ts-time-utils/compare';
const dates = [
new Date('2025-09-15'),
new Date('2025-01-01'),
new Date('2025-12-31'),
new Date('2025-06-15'),
];
// Sort dates
console.log(sortDates(dates, 'asc').map(d => d.toDateString()));
console.log(sortDates(dates, 'desc').map(d => d.toDateString()));
// Find min/max
const earliest = minDate(dates);
const latest = maxDate(dates);
if (earliest && latest) {
console.log('Earliest:', earliest.toDateString());
console.log('Latest:', latest.toDateString());
}
// Find closest to target
const target = new Date('2025-07-01');
const closest = closestDate(target, dates);
if (closest) {
console.log('Closest to July 1:', closest.toDateString());
} Group Dates
Group dates by year, month, or day of week
import { groupDatesByMonth, groupDatesByYear, snapDate } from 'ts-time-utils/compare';
const dates = [
new Date('2025-01-15'),
new Date('2025-01-20'),
new Date('2025-02-10'),
new Date('2025-02-25'),
new Date('2025-03-05'),
];
// Group by month (returns Map<string, Date[]>)
const byMonth = groupDatesByMonth(dates);
byMonth.forEach((monthDates, month) => {
console.log(`${month}: ${monthDates.length} dates`);
});
// Snap to intervals (intervalMinutes)
const meeting = new Date('2025-09-14T14:37:00');
console.log('Original:', meeting.toTimeString());
console.log('Snapped to 15min:', snapDate(meeting, 15).toTimeString());
console.log('Snapped to hour:', snapDate(meeting, 60).toTimeString());