Search code examples
arraysd

How to remove elements from array in D


I have got array of int's in tracksList_filtered variable: [10422, 10681, 10421, 10392, 10616, 10589, 10581, 10423, 10743, 10213, 10613, 10609, 10427, 10484, 10031, 10169, 10695, 10580, 10171, 10703, 10486, 10631, 10642, 10137, 10566, 10704, 10420, 10525, 10209, 10658, 10617, 10127, 10128, 10391, 10602, 10587, 10030, 10393, 10660, 10614, 10485, 10523, 10215, 10029, 10655, 10210, 10659, 10041, 1075, 10425, 10724, 1068, 10657, 10216, 10662, 10211, 10410, 10601, 10644, 10212, 10074, 10696, 10424, 10208, 1074, 10394, 10419, 10426, 10705, 10038, 10661, 10040, 10165, 10396, 10168, 10653, 10610]

I need to remove from it 10422, 10681, 10421 (not by index).

I wrote next code:

auto tracksList_filtered = result.array.map!(a => a[0].coerce!int); 
writeln(tracksList_filtered);
auto x = tracksList_filtered.array.remove(10422, 10681, 10421);
writeln(x);

It's crush with error: range is smaller than amount of items to pop

Example from docs says: "Multiple indices can be passed into remove. In that case, elements at the respective indices are all removed. The indices must be passed in increasing order, otherwise an exception occurs."

int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
assert(remove(a, 1, 3, 5) ==  [ 0, 2, 4, 6, 7, 8, 9, 10 ]);

I tried to check it and placed elements for removing in increasing order:

auto x = tracksList_filtered.array.remove(1068,1074);

But got same exception.


Solution

  • @user1432751's suggestion of setDifference is a good option, but if you do not want to sort your lists you could do:

    auto vals = [1,2,3,4,5,6];
    auto toRemove = [2,3,5];
    auto res = vals.remove!(x => toRemove.canFind(x));
    assert(res == [1,4,6]);