Sort Associative Array by Key

ProtectAndHide ProtectAndHide at gmail.com
Thu Feb 9 10:59:56 UTC 2023


On Thursday, 9 February 2023 at 07:19:08 UTC, 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]]`

Wow. This is an old thread....

.. anyway... how about making custom strings out of the KV pairs:

void main()
{
     import std.conv : to;
     import std.algorithm : sort;
     import std.stdio : writeln;

     auto foo = ["VXE":8, "BZP":5, "JLC":2];

     string[] orderedKeyPairSet;

     foreach (ref kv; foo.byKeyValue)
     {
         orderedKeyPairSet ~= kv.key.to!string ~ ":" ~ 
kv.value.to!string;

     }

     orderedKeyPairSet.sort;

     foreach(ref str; orderedKeyPairSet)
         writeln(str);

}

/*
output:

BZP:5
JLC:2
VXE:8

*/



More information about the Digitalmars-d-learn mailing list