Filter and sort associative array

Steven Schveighoffer schveiguy at
Fri Jan 11 15:48:51 UTC 2019

On 1/11/19 10:20 AM, Head Scratcher wrote:
> I am just learning D. So far, I am impressed by its elegance and power.
> I have an associative array bool[string]. I want to filter it by value 
> (!bool), then extract the keys and sort them. I am struggling with the 
> syntax and working with ranges. I can't find any documentation related 
> to filtering associative arrays.
> This is what I currently have, but it doesn't compile:
> auto sortedStrings = myAssocArray.byKeyValue.filter!((string k,value) => 
> !value).assocArray.keys.sort();

import std.range;
import std.algorithm;
import std.array;

auto sortedStrings = myAssocArray
     .filter!(kvp => !kvp.value) // kvp = key value pair
     .map!(kvp => kvp.key)       // map to the key strings
     .array                      // form a sortable array
     .sort;                      // sort it

Note the nice formatting to show how the range pipeline goes, and allows 
for comments explaining each step.


More information about the Digitalmars-d-learn mailing list