sort - sort an array or list
arr.sort()
arr.sort(cmp)
The sort() method returns a sorted copy of the
array or list arr. The original array is not modified.
The optional cmp argument specifies the comparison to be used:
`<) is used, resulting in an ascending
sort.`<, `>), it is used
to compare elements.Public index, it is
called as a method on the elements to compare them.A new array or list containing the elements of arr in sorted order.
ArgCheck if an incorrect number of arguments
is given
a = [ 3, 1, 4, 1, 5, 9 ]
a.sort()
1 1 3 4 5 9
a.sort(`>)
9 5 4 3 1 1
// Sorting an array of objects by a property 'x'
class Point {
public var x, y;
public proc create(px,py) {x = px; y = py;}
public proc cmpy(b) {return y - b.y;}
}
pts = { Point(10, 2), Point(1, 5), Point(5, 8) }
newpts = pts.sort(proc(a,b) {return a.x - b.x;})
foreach (newpts[i]) { { newpts[i].x, newpts[i].y } }
┌───┐ ┌───┐ ┌────┐
│1 5│ │5 8│ │10 2│
└───┘ └───┘ └────┘
newpts = pts.sort(`cmpy)
foreach (newpts[i]) { { newpts[i].x, newpts[i].y } }
┌────┐ ┌───┐ ┌───┐
│10 2│ │1 5│ │5 8│
└────┘ └───┘ └───┘