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

243
Vistas
Get one value by frequency in JS hash without losing the other keys and values

I am learning Javascript and I have a hash of users like this:

const users = [{id: 1, firstName: "Jose", revenue: 3700, country: "Colombia"}, {id: 2, firstName: "Rodney", revenue: 9100, country: "Germany"}, {id: 3, firstName: "Danny", revenue: 0, country: "United States"},  { id: 4, firstName: "Birgit", revenue: 7700, country: "Germany"}, {id: 5, firstName: "Audra", revenue: 0, country: "Germany"},{id: 6, firstName: "Doreatha", revenue: 0, country: "Colombia"}]

and I'd like to get the frequencies of one key (country) as well as the sum of another key (revenue) of the two most frequent countries. I tried .reduce to get the countries, but the trouble is that it returns an object with no revenues. Here is my code:

const usersByCountry = users.reduce((c, u) => {
  c[u.country] = c[u.country] + 1 || 1;
  return c;
}, {});

And here's the output :

Object { "Colombia": 2, "Germany": 3, "United States": 1 }

Is it even possible to exploit .reduce for this or am I on the wrong track?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can add all required properties to the accumulator object in reduce:

const users = [{id: 1, firstName: "Jose", revenue: 3700, country: "Colombia"}, {id: 2, firstName: "Rodney", revenue: 9100, country: "Germany"}, {id: 3, firstName: "Danny", revenue: 0, country: "United States"},  { id: 4, firstName: "Birgit", revenue: 7700, country: "Germany"}, {id: 5, firstName: "Audra", revenue: 0, country: "Germany"},{id: 6, firstName: "Doreatha", revenue: 0, country: "Colombia"}]

const usersByCountry = users.reduce((acc, u) => {
  acc[u.country] = {
    frequency: (acc[u.country]?.frequency ?? 0) + 1,
    revenue: (acc[u.country]?.revenue ?? 0) + u.revenue
  };
  return acc;
}, {});

console.log(usersByCountry);

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