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 can use the function reduce
to group and build the desired output.
const 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"}]
const result = Object.values(people.reduce((a, {name, age, city, state}) => {
var key = [city, state].join('|');
(a[key] || (a[key] = {city, state, persons: []})).persons.push({name, age});
return a;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }