From 45d6bacf47031a0424f152558514940e1a7a96f5 Mon Sep 17 00:00:00 2001 From: Michiel Vlootman Date: Fri, 16 Jul 2021 10:57:37 +0200 Subject: [PATCH] docs: mention custom sorting (#10812) --- doc/docs.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/doc/docs.md b/doc/docs.md index c29dc01323..c393102d33 100644 --- a/doc/docs.md +++ b/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