Filter and sort associative array
H. S. Teoh
hsteoh at quickfur.ath.cx
Fri Jan 11 15:34:25 UTC 2019
On Fri, Jan 11, 2019 at 03:20:20PM +0000, Head Scratcher via Digitalmars-d-learn 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();
I recommend using std.array.byPair rather than .byKeyValue, like this:
auto sortedStrings = myAssocArray.byPair
.filter!(pair => !pair[1]) // pair[1] is the value
.map!(pair => pair[0]) // pair[0] is the key
.array
.sort;
The .array call is needed because .byPair returns a non-random access
range, which cannot be sorted. So you need to create an array first then
sort that.
Also, there's no need to reconstruct another AA with the filtered
entries -- it allocates a new AA which is wasteful. All you really need
is the filter the keys, then sort the keys.
T
--
If the comments and the code disagree, it's likely that *both* are wrong. -- Christopher
More information about the Digitalmars-d-learn
mailing list