Sort an array of objects

Sort an array of objects

Now there is an object which is Department. He has three attributes: city indicates the city where the department is located. name indicates the name of the department. PersonNum. Indicates the number of people in the department.

Now I want to return the top 5 departments in each city. If the number of people between the two departments is the same. Sort in ascending order according to the dictionary order of city+""+name.

Problem-solving ideas:

  1. Create a dictionary with city names as keys and an array of objects as values.
  2. For each city, sort from largest to smallest according to the number of departments, and then sort according to the lexicographical order of department names from smallest to largest. Take the first five departments and add them to the resulting list.
  3. Return a list of results.
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);

Guess you like

Origin blog.csdn.net/qq_43720551/article/details/131231827