Javascript sort custom comparator function - sorting a sorted array

前端 未结 5 737
你的背包
你的背包 2021-02-03 22:23

I have an array of objects of the following form:

arr[0] = { \'item1\' : 1234, \'item2\' : \'a string\' };

I sort it first by \'item1\'

5条回答
  •  耶瑟儿~
    2021-02-03 23:11

    I'm using this helper in TypeScript:

    // Source
    type ComparatorSelector = (value: T, other: T) => number | string | null;
    
    export function createComparator(...selectors: ComparatorSelector[]) {
      return (a: T, b: T) => {
        for (const selector of selectors) {
          const valA = selector(a, b);
          if (valA === null) continue;
          const valB = selector(b, a);
          if (valB === null || valA == valB) continue;
          if (valA > valB) return 1;
          if (valA < valB) return -1;
        }
        return 0;
      };
    }
    

    // Usage:
    const candidates: any[] = [];
    // ...
    candidates.sort(createComparator(
      (x) => x.ambiguous,
      (_, y) => y.refCount, // DESC
      (x) => x.name.length,
      (x) => x.name,
    ));
    

提交回复
热议问题