Toolbox-XToolbox-X

Sort Array

Sorts an array of various data types based on the provided sorting options.

sortAnArray

The sortAnArray function sorts an array of various data types (strings, numbers, booleans, or objects) based on the provided sorting options.

Function Signatures

function sortAnArray<T extends GenericObject>(array: T[], options: SortByOption<T>): T[]
function sortAnArray<T extends string | number | boolean>(array: T[], options?: OrderOption): T[]

Parameters

  • array: The array to sort, which can contain:
    • Strings
    • Numbers
    • Booleans
    • Objects (with specified fields for sorting)
  • options: Sorting options (optional). The available options are:
    • sortOrder (optional): Defines the order to sort the array:
      • 'asc' (default): Sort in ascending order.
      • 'desc': Sort in descending order.
    • sortByField (optional for object arrays): The field of the object to sort by.

Return Value

  • T[]: Returns the sorted array (a shallow copy of the original).
    • If the array contains strings, it sorts them alphabetically using natural sort.
    • If the array contains numbers, it sorts them numerically.
    • If the array contains booleans, it sorts them by their boolean value (false < true).
    • If the array contains objects, it sorts them by the specified field.

Example Usage

playground.ts

Error Handling

  • If the array is empty or not an array, the function will return the array unchanged.
  • When sorting objects, ensure the sortByField option is provided. If the field is invalid or not resolved, it will position those items at the end.

Notes

  • A shallow copy of the input array is created to ensure the original array remains unmodified.
  • The function sorts strings using a natural sorting order. See naturalSort.

Types

OrderOption

interface OrderOption {
  sortOrder?: 'asc' | 'desc';
}

SortByOption<T>

interface SortByOption<T extends GenericObject> extends OrderOption {
  sortByField: NestedPrimitiveKey<T>;
}

SortOptions<T>

type SortOptions<T> = T extends GenericObject ? SortByOption<T> : OrderOption;

Last updated: Sun, Jun 14, 2026 07:06:16AM (UTC)

On this page