const main = () => {
const sortedData = data.sort((a, b) =>
retrieveByDateAndTime(a) - retrieveByDateAndTime(b)
|| a.text.localeCompare(b.text));
hashLookup.clear(); // Clear the map (optional)
console.log(sortedData); // Display the sorted data
}
// Optimize sorting speed by hashing
const hashLookup = new Map();
const parseDateAndTime = (date, time) => {
const [_month, _date, _year] = date.split('-').map(v => parseInt(v, 10));
const [_hour, _min, _sec] = time.split(':').map(v => parseInt(v, 10));
return new Date(_year, _month - 1, _date, _hour, _min, _sec);
};
const retrieveByDateAndTime = ({ date, time }) => {
const hash = generateHashCode(date + 'T' + time);
let storedDate = hashLookup.get(hash);
if (!storedDate) {
storedDate = parseDateAndTime(date, time);
hashLookup.set(hash, storedDate);
}
return storedDate;
};
// Credit: https://stackoverflow.com/a/8831937/1762224
const generateHashCode = (str) => {
let hash = 0;
for (let i = 0, len = str.length; i < len; i++) {
let chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0;
}
return hash;
}
// Generated with https://www.mockaroo.com
const data = [
{ "date": "06-29-2022", "time": "14:27:00", "text": "Mustang" },
{ "date": "11-10-2022", "time": "20:42:00", "text": "Firebird" },
{ "date": "06-29-2022", "time": "00:22:00", "text": "Mustang" },
{ "date": "11-10-2022", "time": "20:00:00", "text": "E-Series" },
{ "date": "06-29-2022", "time": "10:58:00", "text": "E-Series" },
{ "date": "05-18-2022", "time": "02:59:00", "text": "IS" },
{ "date": "01-14-2023", "time": "09:15:00", "text": "Truck" },
{ "date": "01-13-2023", "time": "00:17:00", "text": "CLS-Class" },
{ "date": "11-10-2022", "time": "18:10:00", "text": "Oasis" },
{ "date": "09-14-2022", "time": "04:15:00", "text": "Monte Carlo" }
];
main(); // Now, call main
.as-console-wrapper { top: 0; max-height: 100% !important; }