I have to turn an array of objects that look this this:
[
{
"id": 15,
"log_name": "default",
"description": "updated",
"properties": "{\"message\":{\"old\":\"It's 2022! Wow!\",\"new\":\"It's 2022!\"}}",
"created_at": "2022-01-05 19:05:12",
"updated_at": "2022-01-05 19:05:12"
}
]
into something like this, sorted by descending date order:
[
{
date: 2022-01-05,
logs: [ array of log objects from that day ]
},
{
date: 2022-01-04,
logs: [ array of log objects from that day ]
},
]
The code I came up with is really ugly and I could use some help, as I loop through the objects three times.
- First, I create an object with dates as the key and arrays of logs as the value
- Then, I convert this object into an array of objects
- Then, I sort of the array by date.
Is there a way to build that final array by only going through the array once?
const groupLogsByDate = (logs: ActivityLog[]): { date: string, logs: ActivityLog[] }[] => {
const groupedLogs: {[date: string]: ActivityLog[]} = {};
Object.values(logs).forEach((log) => {
const date: string = log.created_at.substring(0, 10);
if (date in groupedLogs) {
groupedLogs[date].push(log);
} else {
const newDate: ActivityLog[] = [];
groupedLogs[date] = newDate;
groupedLogs[date].push(log);
}
});
const groupedArray: {date: string, logs: ActivityLog[]}[] = [];
Object.entries(groupedLogs).forEach(([key, val]) => {
const obj = {
date: key,
logs: val,
};
groupedArray.push(obj);
});
// sort the array by date string in descending order
groupedArray.sort((a, b) => {
if (a.date < b.date) {
return 1;
}
if (b.date > a.date) {
return -1;
}
return 0;
});
return groupedArray;
};
```