// utility functions
const groupBy = (prop) => (xs) =>
xs .reduce (
(a, {[prop]: p, ...rest}) => ({...a, [p]: [...(a[p] || []), rest]}),
{}
)
const partition = (pred) => (xs) =>
xs .reduce (([yes, no], x) => pred (x) ? [[...yes, x], no] : [yes, [...no, x]], [[], []])
// main function
const makeGroups = questions => {
const {'no-group': groupless, ...rest} = groupBy ('group') (questions)
const [largeEnough, tooSmall] = partition ((v) => v.length > 1) (Object .values (rest))
const noGroup = [...groupless, ...tooSmall.flat()].sort((a, b) => a.date - b.date)
return {
...Object .fromEntries (
largeEnough
.map (group => group.sort ((a, b) => a .date - b .date))
.sort ((group1, group2) => group1 [0] .date - group2 [0] .date)
.map ((group, i) => [`group ${i + 1}`, group])
),
'no-group': noGroup
}
}
// sample data
const questions = [
{_id: 1, q: 'why?', group: 'no-group', date: '8', selected: false },
{_id: 2, q: 'what?', group: 'A', date: '6', selected: false },
{_id: 3, q: 'when?', group: 'C', date: '7', selected: false },
{_id: 4, q: 'where?', group: 'A', date: '5', selected: false },
{_id: 5, q: 'which?', group: 'B', date: '3', selected: false },
{_id: 6, q: 'who?', date: '0', selected: false }, // no group supplied so will end up in no-group
{_id: 7, q: 'why not?', group: 'B', date: '9', selected: false },
{_id: 8, q: 'who, me?', group: 'A', date: '4', selected: false },
{_id: 9, q: 'where is waldo?', group: 'A', date: '1', selected: false },
{_id: 10, q: 'which way is up?', group: 'B', date: '2', selected: false },
{_id: 11, q: 'when is lunch?', group: 'D', date: '10', selected: false },
];
// demo
console .log (makeGroups (questions))
.as-console-wrapper {max-height: 100% !important; top: 0}