CxJS

getComparer

import { getComparer, sorter, indexSorter } from 'cx/data'; Copied

The comparer utilities create sorting functions for arrays based on field definitions. They support multiple sort fields, custom comparers, and null handling.

getComparer

Creates a comparison function for use with Array.sort().

function getComparer(
  sorters: Sorter[],
  dataAccessor?: (x: any) => any,
  comparer?: (a: any, b: any) => number
): (a: any, b: any) => number

Sorter Definition

interface Sorter {
  field?: string;           // Field name to sort by
  value?: any;              // Selector function or binding
  direction?: "asc" | "desc";  // Sort direction (default: "asc")
  comparer?: (a: any, b: any) => number;  // Custom compare function
}

Example

const compare = getComparer([
  { field: "lastName", direction: "asc" },
  { field: "firstName", direction: "asc" },
]);

const sorted = [...users].sort(compare);

sorter

Creates a function that returns a sorted copy of an array.

function sorter(
  sorters: Sorter[],
  dataAccessor?: (x: any) => any,
  comparer?: (a: any, b: any) => number
): (data: any[]) => any[]

Example

const sortByName = sorter([
  { field: "name", direction: "asc" },
]);

const sorted = sortByName(items);

indexSorter

Creates a function that returns sorted indexes instead of sorted data.

function indexSorter(
  sorters: Sorter[],
  dataAccessor?: (x: any) => any,
  comparer?: (a: any, b: any) => number
): (data: any[]) => number[]

Example

const getSortedIndexes = indexSorter([
  { field: "score", direction: "desc" },
]);

const indexes = getSortedIndexes(players);
// [2, 0, 1] - indexes of items in sorted order

Features

Multiple sort fields

const compare = getComparer([
  { field: "department", direction: "asc" },
  { field: "salary", direction: "desc" },
  { field: "name", direction: "asc" },
]);

Custom value selectors

const compare = getComparer([
  { value: (item) => item.user.name.toLowerCase(), direction: "asc" },
]);

Custom comparers

const compare = getComparer([
  {
    field: "date",
    comparer: (a, b) => new Date(a).getTime() - new Date(b).getTime(),
  },
]);

Null handling

Null values are always sorted to the bottom, regardless of sort direction.

const items = [{ name: "Bob" }, { name: null }, { name: "Alice" }];
const sorted = [...items].sort(getComparer([{ field: "name" }]));
// [{ name: "Alice" }, { name: "Bob" }, { name: null }]

See Also

  • Grid - Grid with built-in sorting
  • Grouper - Group and aggregate data