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

143
Vistas
How can I count the same values ​in the array and create a different array?
[{
    "project_name": "test",
    "status": "High"
},{
    "project_name": "test",
    "status": "Critical"
},{
    "project_name": "test",
    "status": "Critical"
}]

I tried a lot with Object.entries, but I couldn't reach the result I wanted.

Expected Output

[{
  project_name: "test",
  value: 1,
  status: "High",
},
{
  project_name: "test",
  value: 2,
  status: "Critical",
}]

What I want to do is not add a value, but consider more objects in the first array with the same status values. I want to count and group them all.

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

0

  1. Create a temporary object to hold the updated information.
  2. Loop over the array, and for each object create a bespoke key from the product_name and the status.
  3. If the key doesn't exist on the temporary object create a new object from the current one, and add a value property.
  4. Increase the value by one.
  5. Finally you can use Object.values to get at the new objects from the temporary array.

const data=[{project_name:"test",status:"High"},{project_name:"test",status:"Critical"},{project_name:"test",status:"Critical"}];

const temp = {};

for (const obj of data) {
  const { project_name, status } = obj;
  const key = `${project_name}-${status}`;
  temp[key] ??= { ...obj, value: 0 };
  temp[key].value += 1;
}

console.log(Object.values(temp));

Additional documentation

  • Logical nullish assignment

  • Spread syntax

  • Template/string literals


You can also use reduce. The same principles apply (but here you're just initialising an empty object for the accumulator, and passing that through to the next iteration of the array) though the loop might be simpler to understand if you're new to JS.

const data=[{project_name:"test",status:"High"},{project_name:"test",status:"Critical"},{project_name:"test",status:"Critical"}];

const out = data.reduce((acc, obj) => {
  const { project_name, status } = obj;
  const key = `${project_name}-${status}`;
  acc[key] ??= { ...obj, value: 0 };
  acc[key].value += 1;
  return acc;
}, {});

console.log(Object.values(out));

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