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
JavaScript
x
31
31
1
const employees = [
2
{
3
id: 1,
4
name: "john",
5
department: {
6
id: 1,
7
},
8
},
9
{
10
id: 1,
11
name: "Mike",
12
department: {
13
id: 3,
14
},
15
},
16
{
17
id: 1,
18
name: "Leona",
19
department: {
20
id: 1,
21
},
22
},
23
{
24
id: 1,
25
name: "Lara",
26
department: {
27
id: 1,
28
},
29
},
30
];
31
Result Expected:
JavaScript
1
35
35
1
const employees = [
2
{
3
id: 1,
4
name: "john",
5
department: {
6
id: 1,
7
},
8
totalForDeparments: "1/3",
9
},
10
{
11
id: 1,
12
name: "Mike",
13
department: {
14
id: 3,
15
},
16
totalForDeparments: "1/1",
17
},
18
{
19
id: 1,
20
name: "Leona",
21
department: {
22
id: 1,
23
},
24
totalForDeparments: "2/3",
25
},
26
{
27
id: 1,
28
name: "Lara",
29
department: {
30
id: 1,
31
},
32
totalForDeparments: "3/3",
33
},
34
];
35
Advertisement
Answer
First you group by the department.id – then you can iterate the original array adding the correct indexes.
JavaScript
1
19
19
1
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}},];
2
3
var grouped = employees.reduce(function(agg, item) {
4
agg[item.department.id] = agg[item.department.id] || {
5
count: 0,
6
current: 0
7
}
8
agg[item.department.id].count++;
9
return agg;
10
}, {});
11
12
employees.map(function(item) {
13
var data = grouped[item.department.id]
14
data.current++;
15
item.totalForDeparments = data.current + "/" + data.count
16
17
})
18
19
console.log(employees)
JavaScript
1
1
1
.as-console-wrapper {max-height: 100% !important}