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 = [
You could use a Map and a stringified object as key for grouping.
Later render the wanted array with objects of the keys and the grouped persons.
var people = [{ 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" }],
arranged = Array.from(
people.reduce((m, o) => {
var key = JSON.stringify(Object.assign(...['city', 'state'].map(k => ({ [k]: o[k] }))));
return m.set(key, (m.get(key) || []).concat({ name: o.name, age: o.age }));
}, new Map),
([key, persons]) => Object.assign(JSON.parse(key), { persons })
);
console.log(arranged);
.as-console-wrapper { max-height: 100% !important; top: 0; }