Toolbox-XToolbox-X

Natural Sort

Compares two strings using natural sorting order.

naturalSort

The naturalSort function compares two strings using a natural sorting order (e.g., "file2" < "file10"). It optionally supports case-insensitive and locale-aware string chunk comparisons.

Info

Although it compares strings, it was mainly developed for array sorting.

Function Signature

function naturalSort(a: string, b: string, options?: SortNature): number

Parameters

  • a (string): The first string to compare.
  • b (string): The second string to compare.
  • options (SortNature): Optional settings to configure comparison behavior:
    • caseInsensitive (default: true): If true, compares string chunks without case sensitivity.
    • localeAware (default: false): If true, uses localeCompare for string chunk comparisons.

Return Value

  • number:
    • A negative number if a comes before b.
    • A positive number if a comes after b.
    • 0 if the strings are equal.

Example Usage

playground.ts

Types

SortNature

interface SortNature {
  caseInsensitive?: boolean;
  localeAware?: boolean;
}

Aliases

The following aliases can be used for the naturalSort function:

  • naturalSortForString
  • compareNaturally
  • compareSorter

Last updated: Wed, Jun 17, 2026 03:30:54AM (UTC)

On this page