Skip to content
Kavachकवच

Sorting: Two keys

● Beginner3 min

To sort by two keys, give sort_by a tuple: (p.city, p.name) sorts by city, then by name within a city.

type Person {
    name: String
    city: String
    age: Int
}

fn main() {
    const people = [
        Person(name: "Zoe", city: "Pune", age: 30),
        Person(name: "Asha", city: "Delhi", age: 25),
        Person(name: "Omar", city: "Pune", age: 25),
        Person(name: "Bo", city: "Delhi", age: 30),
    ]
    for p in people.sort_by(p => (p.city, p.name)) {
        print("{p.city}: {p.name}")
    }
    print(people.sort_by(p => (-p.age, p.name)).map(.name))
}

The program ran and printed:

kavach run tuple-key.kav

Delhi: AshaDelhi: BoPune: OmarPune: Zoe["Bo", "Zoe", "Asha", "Omar"]
tuple-key.kav: Kavach code, then what running it prints

Tuples compare item by item, so people in the same city are sorted by name. (-p.age, p.name) sorts the oldest first, and people of the same age by name.

The same result comes from two stable sorts, the less important key first. Useful when a key is worked out in a separate step:

type Person {
    name: String
    city: String
}

fn main() {
    const people = [
        Person(name: "Zoe", city: "Pune"),
        Person(name: "Asha", city: "Delhi"),
        Person(name: "Omar", city: "Pune"),
        Person(name: "Bo", city: "Delhi"),
    ]
    const sorted = people.sort_by(.name).sort_by(.city)
    for p in sorted {
        print("{p.city}: {p.name}")
    }
}

The program ran and printed:

kavach run two-keys.kav

Delhi: AshaDelhi: BoPune: OmarPune: Zoe
two-keys.kav: Kavach code, then what running it prints