Home > Mobile >  How can I count the same values ​in the array and create a different array?
How can I count the same values ​in the array and create a different array?

Time:05-27

[{
    "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.

CodePudding user response:

  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


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

  • Related