Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

101
Vistas
Group objects if property values are the same

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'
    },
]
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda