Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!