对对象数组进行排序

对对象数组进行排序

现在有一个对象是Department。他有三个属性:city 表明部门所在的城市。name表示部门的名称。 PersonNum。表示部门的人数。

现在我想要返回每个城市人数前五的部门。如果两个部门之间的人数一样。则按照city+“”+name的字典序升序排序。

解题思路:

  1. 创建一个字典,以城市名称为键,以对象数组为值。
  2. 对于每个城市,按照部门人数从大到小排序,然后按照部门名称的字典序从小到大排序。取前五个部门,将它们添加到结果列表中。
  3. 返回结果列表。
function findTopFiveDepartments(departments) {
    // 1. 创建字典
    const cityDepartments = {};
    for (const d of departments) {
      if (!(d.city in cityDepartments)) {
        cityDepartments[d.city] = [];
      }
      cityDepartments[d.city].push(d);
    }
  
    // 2. 计算 top five 部门
    const result = [];
    for (const [city, depts] of Object.entries(cityDepartments)) {
      const sortedDepts = depts.sort((a, b) => {
        if (a.PersonNum !== b.PersonNum) {
          return b.PersonNum - a.PersonNum;
        } else {
          return a.toString().localeCompare(b.toString());
        }
      }).slice(0, 5);
      // 如果原数组中的元素不足五个,则返回所有元素
      for (const dept of sortedDepts) {
        result.push(dept);
      }
    }
  
    // 3. 返回结果
    return result;
  }
  
  class Department {
    constructor(city, name, PersonNum) {
      this.city = city;
      this.name = name;
      this.PersonNum = PersonNum;
    }
  
    toString() {
      return `${this.city} ${this.name}`;
    }
  }
  

let departments = [
    new Department("New York", "Sales", 50),
    new Department("New York", "Marketing", 30),
    new Department("New York", "Engineering", 80),
    new Department("New York", "Customer Service", 20),
    new Department("New York", "Research", 40),
    new Department("New York", "Research", 50),
    new Department("Los Angeles", "Sales", 60),
    new Department("Los Angeles", "Marketing", 40),
    new Department("Los Angeles", "Engineering", 100),
    new Department("Los Angeles", "Customer Service", 30),
    new Department("Los Angeles", "Research", 50),
    new Department("Los ", "Resear", 50)
];

let topFiveDepartments = findTopFiveDepartments(departments);
console.log(topFiveDepartments);

你可能感兴趣的:(#,LeetCode刻意练习,javascript,前端)