javascript-collections-framework
    Preparing search index...

    Function comparing

    • Returns a comparator that orders values by a key derived from each of them.

      key is called exactly once for each of the two values in every comparison, and its errors propagate. The keys are compared with comparator, or in natural order when it is omitted (so keys of mixed kinds throw ClassCastError). Wrap the key comparator with nullsFirst or nullsLast to allow missing keys.

      Time: O(1) plus two calls of key and one of comparator per comparison.

      Type Parameters

      • T
      • U

      Parameters

      • key: (value: T) => U

        Derives the value to compare.

      • Optionalcomparator: Comparator<U>

        Orders the keys; natural order when omitted.

      Returns Comparator<T>

      The comparator.

      TypeError when key is not a function, or comparator is given but is not a function.

      NullElementError, ClassCastError or TypeError (from the comparator, when natural order is used) as described for naturalOrder.

      const byAge = comparing((user: { age: number }) => user.age)
      const byNickname = comparing((user: { nickname?: string }) => user.nickname, nullsFirst())