Array.sortBy
func Array.sortBy[T, K: Ordered](xs: Array[T], key: func(T): K): Array[T]Array.sortBy returns a new array holding the elements of xs in ascending order of key. The sort is stable, a NaN key sorts after every number, and -0.0 and 0.0 keys are equal.
Details
- Returns a new array;
xsis unchanged. - Calls
keyonce per element, from first to last. - The sort is stable: elements with equal keys keep their order,
-0.0and0.0included. - String keys sort by code point, and a
NaNkey goes after every number key.
Basic examples
Sort words by length:
Array.sortBy(["pear", "fig", "banana"], { x.length() }) // ["fig", "pear", "banana"]Sort records by a field:
type Person = { name: string, age: int }
let people = [Person{ name: "Cy", age: 40 }, Person{ name: "Ann", age: 31 }]
people.sortBy({ x.age }).map({ x.name }) // ["Ann", "Cy"]Scope
An empty array sorts to an empty array:
let empty: Array[int] = []
empty.sortBy({ x }) // []Elements with equal keys keep their order, so "Bob" stays after "Ann":
type Person = { name: string, age: int }
let people = [
Person{ name: "Cy", age: 40 },
Person{ name: "Ann", age: 31 },
Person{ name: "Bob", age: 31 },
]
people.sortBy({ x.age }).map({ x.name }) // ["Ann", "Bob", "Cy"]A string key sorts uppercase ASCII letters before lowercase ones. Sort by String.foldCase to ignore case:
["b", "B", "a", "A"].sortBy({ x }) // ["A", "B", "a", "b"]
["Banana", "apple", "cherry"].sortBy({ x.foldCase() }) // ["apple", "Banana", "cherry"]An accented letter sorts by its code point, after every ASCII letter:
["é", "z", "e", "Z"].sortBy({ x }) // ["Z", "e", "z", "é"]Negate a numeric key to sort in descending order:
[3, 1, 2].sortBy({ -x }) // [3, 2, 1]The keys -0.0 and 0.0 are equal, so their elements keep their order in xs:
[0.0, -0.0, -1.0].sortBy({ x }) // [-1.0, 0.0, -0.0]
[-0.0, 0.0, -1.0].sortBy({ x }) // [-1.0, -0.0, 0.0]A NaN key goes last, after every number, in either direction:
[3.0, 0.0 / 0.0, 1.0, -2.0].sortBy({ x }) // [-2.0, 1.0, 3.0, NaN]
[2.0, 0.0 / 0.0, 1.0].sortBy({ -x }) // [2.0, 1.0, NaN]The elements can be arrays themselves:
[[1, 2, 3], [1], [1, 2]].sortBy({ x.length() }) // [[1], [1, 2], [1, 2, 3]]The element type may include null. Give the key a value for it with ??:
let scores: Array[int | null] = [3, null, 1]
scores.sortBy({ x ?? -1 }) // [null, 1, 3]Pass a named function instead of a lambda:
func vowels(s: string): int {
s.graphemes().countWhere({ "aeiou".contains(x) })
}
["queue", "sky", "area"].sortBy(vowels) // ["sky", "area", "queue"]A key can use the local variables around it. Sort numbers by their distance from a target:
let target = 10
[3, 12, 7, 20].sortBy({ Math.abs(x - target) }) // [12, 7, 3, 20]Call it through . or in a pipe:
["bb", "a", "ccc"].sortBy({ x.length() }) // ["a", "bb", "ccc"]
["bb", "a", "ccc"] | Array.sortBy({ x.length() }) // ["a", "bb", "ccc"]Applications
List the keys of a map from the smallest value to the largest, through its entries:
let stock = Map{ "nut": 3, "bolt": 12, "gear": 7 }
stock.entries().sortBy({ x.value }).map({ x.key }) // ["nut", "gear", "bolt"]Count words and print them from the most frequent, with Array.groupBy:
let words = "the ant and the bee and the ant".split(" ")
for entry in words.groupBy({ x }).entries().sortBy({ -x.value.length() }) {
println("${entry.key}: ${entry.value.length()}")
}the: 3
ant: 2
and: 2
bee: 1Sort by two keys: sort by the second key first, then by the first. The second sort is stable, so it keeps the order of the first among equal keys:
type Person = { name: string, age: int }
let people = [
Person{ name: "Cy", age: 31 },
Person{ name: "Bob", age: 40 },
Person{ name: "Ann", age: 31 },
]
people.sortBy({ x.name }).sortBy({ x.age }).map({ x.name }) // ["Ann", "Cy", "Bob"]Take the names of the fastest runs:
type Run = { name: string, ms: float64 }
func fastest(runs: Array[Run], n: int): Array[string] {
let sorted = runs.sortBy({ x.ms })
sorted.slice(0, Math.min(n, sorted.length())).map({ x.name })
}
let runs = [
Run{ name: "parse", ms: 12.5 },
Run{ name: "check", ms: 30.0 },
Run{ name: "lex", ms: 4.0 },
Run{ name: "run", ms: 9.75 },
]
println(fastest(runs, 3))
println(fastest([], 3))["lex", "run", "parse"]
[]key runs once per element, from the first to the last. A key that logs what it sees shows the order:
let seen: Array[string] = []
["pear", "fig", "kiwi"].sortBy({ seen.push(x); x.length() }) // ["fig", "pear", "kiwi"]
seen // ["pear", "fig", "kiwi"]Properties and relations
With the identity as the key, Array.sortBy gives what Array.sort gives:
let xs = [4, 9, 2, 9, 1]
assert(xs.sortBy({ x }) == xs.sort())The result has the same length as xs, its keys are in ascending order, and xs is unchanged:
let xs = [5, -3, 8, -1]
let ys = xs.sortBy({ Math.abs(x) })
assert(ys.length() == xs.length())
assert(xs == [5, -3, 8, -1])
for i in Array.range(1, ys.length()) {
assert(Math.abs(ys[i - 1]) <= Math.abs(ys[i]))
}When no key is NaN, the first element of the result is what Array.minBy returns, since both keep the first of equal keys:
let words = ["fig", "kiwi", "pea", "plum"]
assert(words.sortBy({ x.length() }).first() == words.minBy({ x.length() }))Array.sortWith with a comparison of the keys gives the same order:
let words = ["pear", "fig", "banana", "kiwi"]
let byLength = words.sortWith(func(a: string, b: string) { a.length() - b.length() })
assert(words.sortBy({ x.length() }) == byLength)Possible issues
Array.sortBy returns a new array and does not sort xs in place. A call whose result is unused changes nothing:
var xs = [3, 1, 2]
xs.sortBy({ x })
println(xs)
xs = xs.sortBy({ x })
println(xs)[3, 1, 2]
[1, 2, 3]The key must be ordered. A bool or a record is not, which is a compile error:
println([1, 2, 3].sortBy({ x > 1 }))
// error: K would be bool, which is not a member of its bound Orderedtype Point = { x: int, y: int }
let points = [Point{ x: 2, y: 1 }, Point{ x: 1, y: 5 }]
println(points.sortBy({ x }))
// error: K would be Point, which is not a member of its bound OrderedReturn one field as the key instead, or compare whole records with Array.sortWith.
A key that can be null has the union type int | null, which is not a single member of Ordered:
let scores: Array[int | null] = [3, null, 1]
println(scores.sortBy({ x }))
// error: K would be int | null, which is not a single member of its bound Ordered; narrow firstGive null a value with ??, as in scores.sortBy({ x ?? -1 }).
Negating a key panics when the negation overflows, as it does for any nonzero unsigned key. Use Array.sortWith for descending order on an unsigned key:
let sizes: Array[uint8] = [uint8(1), uint8(2)]
println(sizes.sortBy({ -x })) // panic: integer overflowConvert the keys to int before subtracting, because b - a on unsigned values panics when b < a:
let sizes: Array[uint8] = [uint8(1), uint8(2)]
sizes.sortWith(func(a: uint8, b: uint8) { int(b) - int(a) }) // [2, 1]A key of a named primitive type is not a member of Ordered, because a named primitive is assignable only to itself, never to its base:
type Celsius = float64
let temps = [Celsius(3.0), Celsius(1.0)]
println(temps.sortBy({ x }))
// error: K would be Celsius, which is not a member of its bound Ordered; unwrap it with float64(...)Unwrap the key with its base type: temps.sortBy({ float64(x) }).
When the first key is NaN, the first element of the result differs from what Array.minBy returns: Array.sortBy puts the NaN key last, while Array.minBy keeps the first element unless a later key is less by <:
[0.0 / 0.0, 2.0, 1.0].sortBy({ x }).first() // 1.0
[0.0 / 0.0, 2.0, 1.0].minBy({ x }) // NaNNegating a key works only for a number; a string key has no negation. For descending order, write a comparison for Array.sortWith. Array.reverse of an ascending sort gives descending order too, but it also reverses the order of equal keys, so the sort is no longer stable:
func longerFirst(a: string, b: string): int {
b.length() - a.length()
}
let words = ["bb", "a", "cc"]
words.sortBy({ x.length() }).reverse() // ["cc", "bb", "a"]
words.sortWith(longerFirst) // ["bb", "cc", "a"]See also
Array.sort · Array.sortWith · Array.reverse · Array.minBy · Array.maxBy · Array.groupBy · Map.entries
