docs: mention custom sorting (#10812)

pull/10833/head
Michiel Vlootman 2021-07-16 10:57:37 +02:00 committed by GitHub
parent cbe4ac703e
commit 45d6bacf47
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 34 additions and 0 deletions

View File

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