sortingtuplessequencenim-lang

How to sort array of tuples alphabetically only based on the first item of the tuple in nim?


if i have a sequence

let my_seq = @[("a", "hello"), ("c", "world"), ("b", "to")]

how can i sort this so that it returns:

let my_seq = @[("a", "hello"), ("b", "to")] ("c", "world")

tried to google it but theres no resources for nim basically


Solution

  • Use the sort procedure from the standard library. If needed, customize it by also providing a comparison function that defines how the items should be compared to each other, and returns an integer indicating their order.

    Simple case:

    import std/algorithm
    
    var my_seq = @[("a", "hello"), ("c", "world"), ("b", "to")]
    
    my_seq.sort()
    
    echo(my_seq)
    

    Demo

    Example comparing the tuples just by their first element (at position 0):

    import std/algorithm
    
    var my_seq = @[("a", "hello"), ("c", "world"), ("b", "to")]
    
    proc myCmp(x, y: (string, string)): int = cmp(x[0], y[0])
    
    my_seq.sort(myCmp)
    
    echo(my_seq)
    

    Demo

    Note that I've changed let to var to make the sequence mutable. If you wanted to keep the original sequence immutable, and just based on that define a new one, use sorted instead:

    import std/algorithm
    
    let my_seq = @[("a", "hello"), ("c", "world"), ("b", "to")]
    
    let my_seq2 = sorted(my_seq)  # or sorted(my_seq, cmp)
    
    echo(my_seq2)
    

    Demo

    All of them output:

    @[("a", "hello"), ("b", "to"), ("c", "world")]