Sort Associative Array by Key

Ali Çehreli acehreli at yahoo.com
Thu Feb 9 19:39:07 UTC 2023


On 2/8/23 23:19, Alexander Zhirov wrote:
 >> foo.byPair
 >>  .array
 >>  .sort!((a, b) => a.key < b.key)
 >>  .map!(a => a.value);
 >
 > Is it possible to specify in `map` to return the result `[a.key] =
 > a.value`? To make the result look like `[key:[val], key:[val]]`

map can return a tuple and std.array.assocArray can make an associative 
array from those tuples:

import std;

void main() {
     auto aa = iota(10)
               .map!(n => tuple(n, n * n))
               .assocArray;
     writeln("Necessarily unsorted:\n", aa);
}

However, as the original question started with an associative array 
anyway, I don't think I understand your question correctly. :)

If you are asking whether an associative array can store in sorted key 
order, then no, it's impossible because associative arrays are hash 
tables, which can't provide that.

But we can visit the elements in sorted order if we sort those keys 
ourselves:

     auto keys = aa
                 .keys  // <- Makes an array by copying the keys
                 .sort;

     writeln("In order:");
     foreach (k; keys) {
         writeln(k, ": ", aa[k]);
     }

Ali



More information about the Digitalmars-d-learn mailing list