docs: mention custom sorting (#10812)
parent
cbe4ac703e
commit
45d6bacf47
34
doc/docs.md
34
doc/docs.md
|
@ -889,6 +889,40 @@ mut users := [User{21, 'Bob'}, User{20, 'Zarkon'}, User{25, 'Alice'}]
|
|||
users.sort(a.age < b.age) // sort by User.age int field
|
||||
users.sort(a.name > b.name) // reverse sort by User.name string field
|
||||
```
|
||||
V also supports custom sorting, through the `sort_with_compare` array method.
|
||||
Which expects a comparing function which will define the sort order.
|
||||
Useful for sorting on multiple fields at the same time by custom sorting rules.
|
||||
The code below sorts the array ascending on `name` and descending `age`.
|
||||
```v
|
||||
struct User {
|
||||
age int
|
||||
name string
|
||||
}
|
||||
|
||||
mut users := [User{21, 'Bob'}, User{65, 'Bob'}, User{25, 'Alice'}]
|
||||
|
||||
custom_sort_fn := fn (a &User, b &User) int {
|
||||
// return -1 when a comes before b
|
||||
// return 0, when both are in same order
|
||||
// return 1 when b comes before a
|
||||
if a.name == b.name {
|
||||
if a.age < b.age {
|
||||
return 1
|
||||
}
|
||||
if a.age > b.age {
|
||||
return -1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
if a.name < b.name {
|
||||
return -1
|
||||
} else if a.name > b.name {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
users.sort_with_compare(custom_sort_fn)
|
||||
```
|
||||
|
||||
#### Array Slices
|
||||
|
||||
|
|
Loading…
Reference in New Issue