Does anyone know of a (lodash if possible too) way to group an array of objects by an object key then create a new array of objects based on the grouping? For example, I hav
Here is a solution inspired from Collectors.groupingBy() in Java:
function groupingBy(list, keyMapper) {
return list.reduce((accummalatorMap, currentValue) => {
const key = keyMapper(currentValue);
if(!accummalatorMap.has(key)) {
accummalatorMap.set(key, [currentValue]);
} else {
accummalatorMap.set(key, accummalatorMap.get(key).push(currentValue));
}
return accummalatorMap;
}, new Map());
}
This will give a Map object.
// Usage
const carMakers = groupingBy(cars, car => car.make);