1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

docs: mention custom sorting (#10812)

This commit is contained in:
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

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.age < b.age) // sort by User.age int field
users.sort(a.name > b.name) // reverse sort by User.name string 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 #### Array Slices