Skip to content

Array<number>.sort() uses lexicographic comparator by default #32593

Closed

Description

TypeScript Version: 3.4.0-dev.201xxxxx

Search Terms:
typed arrays
default comparator
lexicographic comparator
numeric comparator

Code

let a: Array<number> = [12,4];
a.sort();
console.log(a);

Expected behavior:
[4, 12]
Actual behavior:
[12, 4]
Playground Link:
https://codepen.io/greddyatpt/pen/aepoaN?editors=1111

Related Issues:
#18286 is related but it recommends a breaking change. Instead, the default comparator should take the element type into consideration.

Activity

  1. MartinJohns commented on Jul 28, 2019

    @MartinJohns
    Contributor

    This is unrelated to TypeScript, it's up to the runtime.

    Also this is the correct behavior: MDN documentation of Array.prototype.sort()

    The default sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

    Changing this would violate several of the TypeScript Design Goals:

    • Goal 6.: Align with current and future ECMAScript proposals.
    • Goal 7.: Preserve runtime behavior of all JavaScript code.
    • Non-goal 5.: Add or rely on run-time type information in programs, or emit different code based on the results of the type system. Instead, encourage programming patterns that do not require run-time metadata.
  2. RyanCavanaugh commented on Jul 29, 2019

    @RyanCavanaugh
    Member

    TypeScript doesn't change the behavior of JavaScript code.

  3. Rudxain commented on Nov 12, 2024

    @Rudxain
  4. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions