I'm trying to group the objects for the users that have the same location and type value shown in the example below. What would be the best way to approach this?
const diabetics = [
{
type: 'type 1',
location: 'Boston'
email: 'person1@gmail.com'
},
{
type: 'type 2',
location: 'New York'
email: 'person2@gmail.com'
},
{
type: 'type 1',
location: 'Boston'
email: 'person3@gmail.com'
},
{
type: 'type 1',
location: 'Maine'
email: 'person4@gmail.com'
},
]
// expected output
const diabetics = [
{
type: 'type 1',
location: 'Boston'
email: [
'person1@gmail.com',
'person3@gmail.com'
]
},
{
type: 'type 2',
location: 'New York'
email: 'person2@gmail.com'
},
{
type: 'type 1',
location: 'Maine'
email: 'person4@gmail.com'
},
]
You could also get the result using Array.reduce(), creating groups using a key composed of type and location.
Once we have a map keyed on type and location we can use Array.values() to return the desired result:
const diabetics = [ { type: 'type 1', location: 'Boston', email: 'person1@gmail.com' }, { type: 'type 2', location: 'New York', email: 'person2@gmail.com' }, { type: 'type 1', location: 'Boston', email: 'person3@gmail.com' }, { type: 'type 1', location: 'Maine', email: 'person4@gmail.com' }, ]
const result = Object.values(diabetics.reduce ((acc, { type, location, email }) => {
// Create a grouping key, in this case using type and location...
const key = [type, location].join("-");
acc[key] ||= { type, location, email: [] };
acc[key].email.push(email);
return acc;
}, {}))
console.log('Result:', result);