I am using JavaScript native reduce, however I want to slightly change in the grouping to get my desired result. I have an array as follows:
const people = [
I have built a generic group by reducer, you pass it the keys by which you want to group and it gives you a custom reducer function. This reducer gives you an object indexed by a (composed or simple) key containing an array of items that share this key. You can reuse it to have it grouped by the key(s) you want to.
Here are two examples.
const people = Object.freeze([{
name: "John",
age: 23,
city: "Seattle",
state: "WA"
}, {
name: "Mark",
age: 25,
city: "Houston",
state: "TX"
}, {
name: "Luke",
age: 26,
city: "Seattle",
state: "WA"
}, {
name: "Paul",
age: 28,
city: "Portland",
state: "OR"
}, {
name: "Matt",
age: 21,
city: "Oakland",
state: "CA"
}, {
name: "Sam",
age: 24,
city: "Oakland",
state: "CA"
}]);
const groupByReducer = (group) =>
(result, row) => {
const keygroup = group.map((v) => row[v]);
const key = keygroup.join(':');
if (result[key])
result[key].push(row);
else
result[key] = [row];
return result;
};
const byCityState = people.reduce(
groupByReducer(['city', 'state']), {});
const byState = people.reduce(groupByReducer(['state']), {});
console.log(byCityState);
console.log(byState);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}