JSFiddle - React, Tailwind, and code Playground

by jonahe

JavaScript

const employees = [
      {
        title: 'John Doe',
        departments: [
          { name: 'Marketing', slug: 'marketing'},
          { name: 'Sales', slug: 'sales'},
          { name: 'Administration', slug: 'administration'},
        ]
      },
      {
        title: 'John Doe Junior',
        departments: [
          { name: 'Operations', slug: 'operations'},
          { name: 'Sales', slug: 'sales'},
        ]
      },
      {
        title: 'Rick Stone',
        departments: [
          { name: 'Operations', slug: 'operations'},
          { name: 'Marketing', slug: 'marketing'},
        ]
      },
 ];

const departmentMatchesName = name => department => department.slug == name;
const isInDepartment = 
	departmentToCheck => 
  	employer => employer.departments.some(departmentMatchesName(departmentToCheck));

var departments = [];
var found = function (nameToCheck) {
  return departments.some(function (departmentName) {
    return departmentName == nameToCheck;
  });
}
employees.forEach((employee) => {
    employee.departments.forEach((department) => {
        if (!found(department.slug)) { 
        	departments.push(department.slug); 
        }
		});
});
console.log(departments);

const employeesGroupedByDepartments = {};
departments.forEach((department) => {
    employeesGroupedByDepartments[department] = employees.filter(isInDepartment(department));
});

console.log('result', employeesGroupedByDepartments)