如何按mm/dd/yyyy格式的paymentDate排序对象数组?
Hey there! Let's get that contributions array sorted properly by year, month, and day—your current code only handling year-level sorting makes total sense why it's not working, since we need to account for the full date structure. Here are two solid approaches to fix this:
The simplest way is to convert each paymentDate string into a native JavaScript Date object, then compare their timestamps. This works because the Date constructor can reliably parse mm/dd/yyyy formatted strings in modern browsers and Node.js.
// Create a copy of the array first to avoid modifying the original const sortedContributions = [...contributions].sort((a, b) => { // Convert paymentDate strings to Date objects const dateA = new Date(a.paymentDate); const dateB = new Date(b.paymentDate); // Subtract dates to get a sortable value: negative = a comes first, positive = b comes first return dateA - dateB; });
- Use the spread operator (
[...contributions]) to create a copy of your array—this keeps the original data intact (a good practice for immutability). - This will sort the array in ascending order (oldest to newest). To sort in descending order, just reverse the subtraction:
return dateB - dateA;.
If you want full visibility into the sorting logic (or need to handle edge cases with date parsing), you can split the paymentDate string into year, month, and day components, then compare them one by one.
// Helper function to split mm/dd/yyyy into numeric values const extractDateParts = (dateString) => { const [month, day, year] = dateString.split('/').map(Number); return { year, month, day }; }; const sortedContributions = [...contributions].sort((a, b) => { const partsA = extractDateParts(a.paymentDate); const partsB = extractDateParts(b.paymentDate); // First compare years if (partsA.year !== partsB.year) { return partsA.year - partsB.year; } // If years match, compare months if (partsA.month !== partsB.month) { return partsA.month - partsB.month; } // If months match, compare days return partsA.day - partsB.day; });
- This method is more verbose but gives you full control—great if you need to adjust sorting logic later (e.g., handle leap years, or add time comparison if needed).
- Like the first solution, reverse the subtraction values for descending order.
- Never sort date strings directly: A string like
"12/31/2022"will come after"01/01/2023"in string comparison, which is the opposite of the actual date order. - Always work with a copy of the array: The
sort()method mutates the original array, so creating a copy prevents unintended side effects.
内容的提问来源于stack exchange,提问作者Alex Liosatos

