Difference between revisions of "Sort"

From MiniScript Wiki
Jump to navigation Jump to search
(Added example for sorting by property)
Line 22: Line 22:
 
== Example ==
 
== Example ==
  
<ms>a = [5,3,4,1,2]; a.sort // results in a == [1, 2, 3, 4, 5]</ms>
+
Sorting numeric list in-place:
 +
 
 +
<ms>
 +
a = [5,3,4,1,2]
 +
a.sort         // results in a == [1, 2, 3, 4, 5]</ms>
 +
 
 +
Sorting objects / maps by some property:
 +
 
 +
<ms>
 +
// 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]
 +
</ms>
  
 
[[Category:Intrinsic Functions]]
 
[[Category:Intrinsic Functions]]
 
[[Category:List Methods]]
 
[[Category:List Methods]]

Revision as of 10:42, 1 February 2022

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 Default Value Meaning
self list list to sort
byKey optional if given, sort each element by indexing with this key.

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 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]