JS Second .sort打破了链中的第一个.sort

时间:2018-10-02 16:07:15

标签: javascript sorting

我有以下代码。我想先按姓氏排序,然后按访问权限排序,同时保持第一个函数的字母排序

let sorted_list = employee_list
      .sort((a, b) => {
        let first = a.name.split(' ')[1].toUpperCase();
        let second = b.name.split(' ')[1].toUpperCase();

        return (first < second) ? -1 : (first > second) ? 1 : 0;
      })
      .sort((a, b) => {
        return b.coaching_access - a.coaching_access;
      })
      .map(this.renderEmployee);

2 个答案:

答案 0 :(得分:0)

合并以下两种类型

let sorted_list = employee_list
  .sort((a, b) => {
    let first = a.name.split(' ')[1].toUpperCase();
    let second = b.name.split(' ')[1].toUpperCase();
    return first > second || b.coaching_access - a.coaching_access;
  })
  .map(this.renderEmployee);

示例

let employee_list = [{name: "a b", coaching_access : 1}, {name: "a a", coaching_access : 2}, {name: "a c", coaching_access : 1}, {name: "a a", coaching_access : 1}, {name: "a a", coaching_access : 3}]

employee_list
  .sort((a, b) => {
    let first = a.name.split(' ')[1].toUpperCase();
    let second = b.name.split(' ')[1].toUpperCase();
    return first > second || b.coaching_access - a.coaching_access;
});

console.log(employee_list);

答案 1 :(得分:0)

排序应用于完整列表。如果您遇到这种情况,我想您需要类似的东西:

let sorted_list = employee_list
  .sort((a, b) => {
    let first = a.name.split(' ')[1].toUpperCase();
    let second = b.name.split(' ')[1].toUpperCase();

    return (first < second) ? -1 : (first > second) ? 1 : b.coaching_access - a.coaching_access;
  })
  .map(this.renderEmployee);

这样,coaching访问属性用于解开相同的名称。