I am looking to sort an array of objects by pickup time, but I need the times to be formatted like they are in the array below after sorting. Obviously, the issue I am running into is you cannot use .sort() to sort strings like you can with integers.
Is there any way to sort these from earliest times to latest times using .sort()? Or if not, is there a way to format them as integers and then reformat them and push them back into their respective places in the object?
[{pickupTime='10:30 AM', pickupTime='4:00 AM', pickupTime='6:30 AM',pickupTime='12:00 PM',pickupTime='1:00 PM'}, [{pickupTime='9:00 AM',pickupTime='6:00 PM', pickupTime='4:00 PM', pickupTime='8:00PM'}, {pickupTime='4:00 PM', pickupTime='7:00PM', pickupTime='5:30 PM'}]
This is what I am using to format them in Apps Scripts.
for(var k = 0 ; k < abc.length ; k ){
let singleDelivery = sourceRange[abc[k]];
let pickTime = new Date(singleDelivery[8])
let pickTime2 = Utilities.formatDate(pickTime, "EST", 'h:mm a');
let dropTime = new Date(singleDelivery[10]);
let dropTime2 = Utilities.formatDate(dropTime, "EST", 'h:mm a');
let deliveryDetailsArray = {
"orderName": singleDelivery[1],
"driverName": singleDelivery[2],
"deliveryDate" : singleDelivery[7],
"pickupTime": pickTime2,
"dropoffTime": dropTime2,
"pickUpAddress": singleDelivery[11],
"dropoffAddress": singleDelivery[12],
"routingType": singleDelivery[13]
}
deliveryDetails.push(deliveryDetailsArray);
sorted = deliveryDetails.sort((a, b) => a.pickupTime - b.pickupTime)
}
CodePudding user response:
Don't format the date yet when declaring devlieryDetailsArray
, keep it as pickTime
raw date object (from your code I don't know for sure that it's a regular JS date, but I assume so).
Do the sort, then just format it later.
const sorted = deliveryDetails.sort((a,b) => a.pickupTime - b.pickupTime);
const formattedDeliveryDetails = sorted.map(deliveryDetail => ({...deliveryDetail, pickupTime: Utilities.formatDate(deliveryDetail.pickupTime, "EST", 'h:mm a') }));