Skip to content
Advertisement

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:

    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",
  },
];

Advertisement

Answer

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}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement