Hex Core JS
    Preparing search index...

    Function compareObjects

    • Returns a comparison function that compares two objects using the given keys or functions to get values and comparison function(s). Works in a multi-level fashion when given multiple keys or value-getter functions.

      Type Parameters

      Parameters

      • keysOrGetValues: keyof T | ((object: T) => any) | (keyof T | ((object: T) => any))[]

        An individual or array of either keys of the type T or functions that accept an object of type T and return a value to use for comparison.

      • comparisonFunctions: ComparisonFunction<any> | ComparisonFunction<any>[]

        The comparison function or functions to use to compare each pair of values.

      Returns ComparisonFunction<T>

      Lengths of keysOrGetValues and comparisonFunctions (if arrays) must match.

      const data = [{x: "a", y: "a"}, {x: "b", y: "c"}, {x: "a", y: "z"}];
      const compare = compareObjects(["x", "y"], compareStringsAsc());
      data.sort(compare);
      // [{ x: "a", y: "a" }, { x: "a", y: "z" }, { x: "b", y: "c" }]
      const data = [{x: "a", y: "a"}, {x: "b", y: "c"}, {x: "a", y: "z"}];
      const compare = compareObjects(e => e.x + e.y, compareStringsAsc());
      data.sort(compare);
      // [{ x: "a", y: "a" }, { x: "a", y: "z" }, { x: "b", y: "c" }]
      const data = [{x: "a", y: "1"}, {x: "b", y: "3"}, {x: "a", y: "26"}];
      const compare = compareObjects(["x", e => parseInt(e.y)], [compareStringsAsc(), compareNumbersDesc()]);
      data.sort(compare);
      // [{ x: "a", y: "26" }, { x: "a", y: "1" }, { x: "b", y: "3" }]