I am a beginner in programming and solving exercises for logic building.
I have an array of employees. Like This One (Actual array has more data, this is just an example):
let arr = [
{
name: 'Tom',
department: {
name: 'admin',
},
},
{
name: 'Chris',
department: {
name: 'account',
},
},
];
Now I want to return Employees with the Highest count in the Department
I have counted number of employees per department
const counts = {};
employees.forEach( (employee)=>{
counts[employee.department.name] = (counts[employee.department.name] || 0) + 1;
});
console.log(counts) // { Accounts: 1, admin: 1 }
But I want to return Employees with highest count of with Department and instead of number of employees I want to return each employee object.
This is the expected output:
{
name: 'Employee1'
{
department:'Admin'
}
},
{
name: 'Employee2'
{
department:'Admin'
}
},
{
name: 'Employee3'
{
department:'Admin'
}
}
I just need a guide for what to do next.
Thanks
Instead of number, I store employees by their department in an object (hashmap). Then to extract the largest one, I've created a function that returns an object having the department and list of employees.
Feel free to run the code below and see the results.
let employees = [
{
name: "Tom",
department: {
name: "admin"
}
},
{
name: "Chris",
department: {
name: "account"
}
}
];
const counts = {};
employees.forEach((employee) => {
counts[employee.department.name] = (
counts[employee.department.name] || []
).concat(employee.name);
});
console.log(counts); // {admin: ['Tom'], account: ['Chris']}
function getLargest(map) {
let max = 0;
let biggestDepartment = null;
Object.entries(map).forEach(([department, arr]) => {
if (max < arr.length) {
max = arr.length;
biggestDepartment = department;
}
});
return {
name: biggestDepartment,
employees: map[biggestDepartment]
}
}
console.log(getLargest(counts))
So my solution is that you first group the employees w.r.t. department and then you can get the department with the highest employee count using the .length property.
const getGroupDepartments = (employees) => {
const groupedDepartments = {};
employees?.forEach((employee) => {
groupedDepartments[employee.department.name] = groupedDepartments[employee.department.name] ?
[...groupedDepartments[employee.department.name], employee] : [employee]
});
return groupedDepartments
}
const getLargestDepartment = (employees) => {
const departments = getGroupDepartments(employees)
let largestDepartment;
for (const department in departments) {
if(largestDepartment?.length < departments[department].length || !largestDepartment){
largestDepartment = departments[department]
}
}
return largestDepartment
}