Difference between revisions of "Sort"
Jump to navigation
Jump to search
(Added example for sorting by property) |
m |
||
| (3 intermediate revisions by 2 users not shown) | |||
| Line 7: | Line 7: | ||
{| class="wikitable" | {| class="wikitable" | ||
|- | |- | ||
| − | ! Parameter Name !! | + | ! Parameter Name !! Type !! Meaning |
|- | |- | ||
| ''self'' || list || list to sort | | ''self'' || list || list to sort | ||
|- | |- | ||
| − | | ''byKey'' || | + | | ''byKey'' || any || if given, sort each element by indexing with this key. |
| + | |- | ||
| + | | ''ascending'' || number, default = 1 || pass 0 or <c>false</c> to sort in descending order. | ||
|} | |} | ||
| Line 27: | Line 29: | ||
a = [5,3,4,1,2] | a = [5,3,4,1,2] | ||
a.sort // results in a == [1, 2, 3, 4, 5]</ms> | a.sort // results in a == [1, 2, 3, 4, 5]</ms> | ||
| + | |||
| + | Sorting in reverse order: | ||
| + | |||
| + | <ms> | ||
| + | b = [1,3,0,8,7] | ||
| + | b.sort null, false // results in b == [8, 7, 3, 1, 0]</ms> | ||
Sorting objects / maps by some property: | Sorting objects / maps by some property: | ||
| Line 47: | Line 55: | ||
people = [john, ursula, anna] | people = [john, ursula, anna] | ||
| − | people.sort | + | people.sort "age" // results in people == [ursula, john, anna] |
| − | people.sort | + | people.sort "name" // results in people == [anna, john, ursula] |
</ms> | </ms> | ||
[[Category:Intrinsic Functions]] | [[Category:Intrinsic Functions]] | ||
[[Category:List Methods]] | [[Category:List Methods]] | ||
Latest revision as of 16:55, 14 June 2026
sort sorts a list in place. With null or no argument, this sorts the list elements by their own values.
See also: shuffle
Arguments
| Parameter Name | Type | Meaning |
|---|---|---|
| self | list | list to sort |
| byKey | any | if given, sort each element by indexing with this key. |
| ascending | number, default = 1 | pass 0 or false to sort in descending order.
|
Usage Notes
With the byKey argument, each element is indexed by that argument, and the elements are sorted by the result. (This only works if the list elements are maps, or they are lists and byKey is an integer index.)
Example
Sorting numeric list in-place:
a = [5,3,4,1,2]
a.sort // results in a == [1, 2, 3, 4, 5]
Sorting in reverse order:
b = [1,3,0,8,7]
b.sort null, false // results in b == [8, 7, 3, 1, 0]
Sorting objects / maps by some property:
// Let's consider people
Person = {}
newPerson = function(name, age)
p = new Person
p.name = name
p.age = age
return p
end function
john = newPerson("John", 30)
ursula = newPerson("Ursula", 20)
anna = newPerson("Anna", 40)
people = [john, ursula, anna]
people.sort "age" // results in people == [ursula, john, anna]
people.sort "name" // results in people == [anna, john, ursula]