How to sort based on incomplete criteria?

前端 未结 3 1583
旧巷少年郎
旧巷少年郎 2021-01-15 22:05

First I tried passing my own function to Array.sort, but it doesn\'t sort correctly. Notice how \'c\' comes before \'a\' in the resul

3条回答
  •  没有蜡笔的小新
    2021-01-15 22:49

    Maybe something like this

    const sorted = ['a', 'b', 'c', 'd']; // I do NOT have access to this
    const unsorted = ['c', 'd', 'a', 'b'];
    
    const a_before_b = (a, b) => {
      if (a == 'a' && b == 'd') return true;
      if (a == 'b' && b == 'c') return true;
      if (a == 'a' && b == 'c') return true;
    
    }
    
    const b_before_a = (a, b) => {
      if (b == 'a' && a == 'c') return true;
      if (b == 'b' && a == 'c') return true;
    }
    
    const mySortingFunction = (a, b) => {
      if (a_before_b(a, b)) return -1;
      if (b_before_a(a, b)) return 1;
      return 0;
    }
    
    // doesn't produce correct sorting 
    console.log(unsorted.sort(mySortingFunction));

提交回复
热议问题