Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to enumare objects and total of them with the same key with another object in array js

I’m populing a pdf template with an array of employees, and now I need to count the number of employees working in a same department, I found a way to count the total of concurrences but I can’t enumarate the employee working in the department and the total of them. Can you help me? Thanks!!!

For example, I have this array of objects

const employees = [
  {
    id: 1,
    name: "john",
    department: {
      id: 1,
    },
  },
  {
    id: 1,
    name: "Mike",
    department: {
      id: 3,
    },
  },
  {
    id: 1,
    name: "Leona",
    department: {
      id: 1,
    },
  },
   {
    id: 1,
    name: "Lara",
    department: {
      id: 1,
    },
  },
];

Result Expected:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    const employees = [
  {
    id: 1,
    name: "john",
    department: {
      id: 1,
    },
    totalForDeparments: "1/3",
  },
  {
    id: 1,
    name: "Mike",
    department: {
      id: 3,
    },
    totalForDeparments: "1/1",
  },
  {
    id: 1,
    name: "Leona",
    department: {
      id: 1,
    },
    totalForDeparments: "2/3",
  },
  {
    id: 1,
    name: "Lara",
    department: {
      id: 1,
    },
    totalForDeparments: "3/3",
  },
];

>Solution :

First you group by the department.id – then you can iterate the original array adding the correct indexes.

const employees = [{id:1,name:"john",department:{id:1}},{id:1,name:"Mike",department:{id:3}},{id:1,name:"Leona",department:{id:1}},{id:1,name:"Lara",department:{id:1}},];

var grouped = employees.reduce(function(agg, item) {
  agg[item.department.id] = agg[item.department.id] || {
    count: 0,
    current: 0
  }
  agg[item.department.id].count++;
  return agg;
}, {});

employees.map(function(item) {
  var data = grouped[item.department.id]
  data.current++;
  item.totalForDeparments = data.current + "/" + data.count

})

console.log(employees)
.as-console-wrapper {max-height: 100% !important}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading