I'm learning JS and from a background in SQL I'm trying to understand the best way to simulate a "Group By" query on an array of objects. For example, I want to return the most recent "Task" that has not been completed yet. Is this possible with ES6 Map function?
[
{
"id": 581337,
"date_due": "2021-10-04",
"task": "Client Billing Activity Review",
"is_completed": 1,
},
{
"id": 581338,
"date_due": "2021-12-10",
"task": "Client Billing Activity Review",
"is_completed": 0,
},
{
"id": 581339,
"date_due": "2022-01-09",
"task": "Client Billing Activity Review",
"is_completed": 0,
},
{
"id": 581340,
"date_due": "2022-04-10",
"task": "Client Billing Activity Review",
"is_completed": 0,
}
]
In SQL my query would be:
select task, min(date_due) as next due_date
from table
where date_due > today()
and is_completed = 0
group by task
JS sandbox here: https://parsebox.io/jamieroyce/tmbghkcyfwkh
Cleanest solution I could find to do this is: Create a dictionary, filter out any records not needed, loop through the dictionary and keep the task with the next closest date:
const dict = {};
input.filter(n => n.is_completed === 0 && new Date(n.date_due) - new Date() > 0)
.forEach(n => {
dict[n.task] = dict[n.task] || n;
if (new Date(dict[n.task].date_due) < new Date(n.date_due)) {
dict[n.task] = n;
}
});
return dict;