const groupBy = (collection, extractKey) =>
collection.reduce((acc, item) => {
const key = extractKey(item);
acc[key] ??= [];
acc[key].push(item);
return acc;
}, {});
const data = groupBy(array, (person) => person.role);
Object.groupBy(array, (person) => person.role);
const parseDate = (date) => Date.parse(date.split('/').reverse().join('-'));
const findClosest = (list, date = (new Date()).toLocaleDateString('en-GB')) => {
const findDate = parseDate(date);
return list.reduce(
(acc, cur) => {
const delta = parseDate(cur.date) - findDate;
return (delta >= 0 && delta < acc.delta) ? { delta, el: cur } : acc;
},
{ delta: Number.MAX_SAFE_INTEGER, el: null },
).el;
};
const result = Object.values(cars.reduce((acc, n) => (
(acc[n.make] ??= { make: n.make, attr: [] }).attr.push(n),
acc
), {}));
function group(data, key, val = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const getVal = val instanceof Function ? val : n => n[val];
const result = new Map;
for (const n of data) {
const k = getKey(n);
result.set(k, result.get(k) ?? []).get(k).push(getVal(n));
}
return result;
}
const result = Array.from(
group(cars, 'make'),
([ make, attr ]) => ({ make, attr })
);