arraysindexingslicedphobos

std.algorithm.remove() duplicating array items?


I have an array that I need to remove items from, by index. It for some reason duplicates other items in the array to take the removed item's place. Here is an example of the issue.

import std.stdio: writeln;
import std.algorithm: remove;

void main() {
    string[string] assocArray = [
        "firstvalue": "Number 1",
        "secondvalue": "Number 2",
        "thirdvalue": "Number 3",
        "fourthvalue": "Number 4",
        "fifthvalue": "Number 5",
        "sixthvalue": "Number 6",
    ];

    string[] assocArrayKeys = assocArray.keys(); // I know these aren't in the same order as the literal.

    writeln(assocArrayKeys);
    // ["thirdvalue", "fourthvalue", "fifthvalue", "sixthvalue", "firstvalue", "secondvalue"]

    assocArrayKeys.remove(0);
    assocArrayKeys.remove(5);

    writeln(assocArrayKeys);
    // ["fourthvalue", "fifthvalue", "sixthvalue", "firstvalue", "secondvalue", "secondvalue"]
    // It did remove them, but there are now two "secondvalue"s.
}

Any help would be appreciated.


Solution

  • This was somewhat of a silly question. Someone pointed out that in the documentation, it says that it has to be reassigned to itself.

    Note that remove does not change the length of the original range directly; instead, it returns the shortened range. If its return value is not assigned to the original range, the original range will retain its original length, though its contents will have changed.

    Source: https://dlang.org/library/std/algorithm/mutation/remove.html

    The solution is as follows:

    assocArraykeys = assocArrayKeys.remove(0);
    assocArrayKeys = assocArrayKeys.remove(5);
    

    This seems a little silly and unintuitive to me though because it is in std.algorithm.mutation. Keyword: mutation.