I have an array with objects like this:
[
{date: 2023-05-06, group: 'groupA'},
{date: 2023-05-05, group: 'group1'},
{date: 2023-05-07, group: 'groupA'},
{date: 2023-05-08, group: 'group1'},
]
I would like to get an array where the newest element is the first and the elements are grouped by the group
property which is a string.
Expected result:
[
{date: 2023-05-08, group: 'group1'}, // newest in array
{date: 2023-05-05, group: 'group1'}, // second newest in same group
{date: 2023-05-07, group: 'groupA'}, // second newest in array
{date: 2023-05-06, group: 'groupA'}, // second newest in same group
]
3
Answers
We’d create a
groupBy
function to allow us to group any array by an arbitrary key.We’ll sort our input by date first then group.
Finally we’ll get all values and flatten using Object.values() and Array.flat():
You need to find max date per group before you can decide which group sorts first. Then for items within same group you sort them by date:
Looking at the result exemple you provided, I think this would work for you.
You can solve this by grouping by
group
and sorting each group individually. Finally, you can merge the sorted groups in a single array (this should keep the array sorted because you are iterating it by order)