Function compareBy

  • Creates a comparator that uses a selector to transform values before they are compared.

    The selector may be either an object key (typically a string) or a function.

    A comparator may also be provided as the second argument to compare the transformed values. Otherwise, naturalOrder will be used by default.

    Type Parameters

    • K extends string | number | symbol
    • V = unknown

    Parameters

    • key: K

      objects will be compared by accessing the property with this key

    • Optionalcomparator: Comparator<V>

      compares the property values

    Returns CompareByKey<K, V>

    a new comparator

    const list = [
    { color: "red" },
    { color: "green" },
    { color: "blue" },
    ];
    // sorts the list by the color property alphabetically
    list.sort(compareBy("color"));
    const list = [
    { x: { y: 42 } },
    { x: { y: 93 } },
    { x: { y: 10 } },
    ];
    // sorts the list by the inner 'y' property in reverse order
    list.sort(
    compareBy(
    (element) => element.x.y,
    reverseOrder,
    )
    );
  • Creates a comparator that uses a selector to transform values before they are compared.

    The selector may be either an object key (typically a string) or a function.

    A comparator may also be provided as the second argument to compare the transformed values. Otherwise, naturalOrder will be used by default.

    Type Parameters

    • T
    • U

    Parameters

    • selector: SelectorFn<T, U>

      a function that transforms a value into another value to be compared

    • Optionalcomparator: Comparator<U>

      compares the transformed values

    Returns Comparator<T>

    a new comparator

    const list = [
    { color: "red" },
    { color: "green" },
    { color: "blue" },
    ];
    // sorts the list by the color property alphabetically
    list.sort(compareBy("color"));
    const list = [
    { x: { y: 42 } },
    { x: { y: 93 } },
    { x: { y: 10 } },
    ];
    // sorts the list by the inner 'y' property in reverse order
    list.sort(
    compareBy(
    (element) => element.x.y,
    reverseOrder,
    )
    );