JavaScript Sort

sort() orders the elements of an array. Without a comparator it converts elements to strings and sorts them alphabetically, which breaks numbers. Pass (a, b) => a - b for a numeric sort. This playground sorts a copy so your input stays intact.

Syntax

arr.sort((a, b) => a - b)

Examples

Input Arguments Output
[3, 1, 2] (a, b) => a - b [1, 2, 3]
[1, 10, 2] [1, 10, 2]
↳ The default sort compares as strings: 10 comes before 2.

When to use it

  • Sort numbers, names or dates before displaying them.
  • Rank results by a computed score.

Gotchas

  • Default sort is lexicographic: [1, 10, 2] stays [1, 10, 2] because "10" < "2" as strings.
  • Native sort() mutates the array in place. Copy it first ([...arr].sort()) to stay immutable.

Try it live

Type your input and see Sort transform it instantly.

Sort()

Type above to see the result…

Want to go further? Chain Sort with other functions, pipe one output into the next and watch your data transform in the visual Playground.

Related functions

© 2026 Heifara Buval