• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

109
Vistas
Counting the occurrences of an object in an array of objects based on a key

I have an array of objects as follows :

let people = [
              { name: "Emily", age: 15 }, { name: "Emma", age: 16 }, 
              { name: "Stacy", age: 18 }, { name: "Emily", age: 15 },
              { name: "Jennifer", age: 12 }  
             ];

I need to return the result containing the age as the key and frequency as it's corresponding value as follows :

{ 15 : 2, 16 : 1, 18 : 1, 12 : 1 }

I wish I could implement this using both forEach() and reduce().

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Using Array#reduce:

const people = [ { name: "Emily", age: 15 }, { name: "Emma", age: 16 }, { name: "Stacy", age: 18 }, { name: "Emily", age: 15 }, { name: "Jennifer", age: 12 } ];

const ageCount = people.reduce((map, { age }) => ({
  ...map,
  [age]: (map[age] || 0) + 1
}), {});

console.log(ageCount);

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda