Sorting

sort returns a new array in ascending order. sort_by takes a comparator function for custom ordering. Both leave the original unchanged.

sort returns a new array sorted ascending. Works on numbers and strings.

fn main() {
  nums = [5, 2, 8, 1, 9, 3]
  println(sort(nums))
  println(nums)

Strings sort lexicographically.

  words = ["banana", "apple", "cherry"]
  println(words.sort())

sort_by takes a comparator: fn(a, b) returns true if a should come before b.

  desc = nums.sort_by(fn(a, b) a > b)
  println(desc)

Use sort_by for custom ordering. Sort by absolute value:

  mixed = [-3, 1, -2, 4]
  by_abs = mixed.sort_by(fn(a, b) abs(a) < abs(b))
  println(by_abs)

Duplicates are preserved.

  println([3, 1, 3, 2, 1].sort())

Empty and single-element arrays are fine.

  println([].sort())
  println([42].sort())
}
$ pyr run sort.pyr
[1, 2, 3, 5, 8, 9]
[5, 2, 8, 1, 9, 3]
["apple", "banana", "cherry"]
[9, 8, 5, 3, 2, 1]
[1, -2, -3, 4]
[1, 1, 2, 3, 3]
[]
[42]