Basic module

array_unordered_remove_by_value

procedure · 1 overloadSource

Removes every element equal to item, each by moving the last element into its place; returns how many were removed.

With $stop_after_first set it removes at most one. Equality is ==, or compare when given. The order of the survivors is not kept. Each removal searches from the start again, so removing many matches from a long array is quadratic.

ExampleOpen in playground ↗
values: [..] int;
array_add(*values, 1, 2, 1, 3, 1);
removed := array_unordered_remove_by_value(*values, 1);
assert(removed == 3 && values.count == 2);

once := array_unordered_remove_by_value(*values, 2, stop_after_first = true);
assert(once == 1 && values.count == 1 && values[0] == 3);
array_free(values);
array_unordered_remove_by_value :: (
    array: *[] $T,
    item: T,
    $stop_after_first := false,
    $compare: (T, T) -> bool = null
) -> s64

Removes every element equal to item, each by moving the last element into its place; returns how many were removed.

With $stop_after_first set it removes at most one. Equality is ==, or compare when given. The order of the survivors is not kept. Each removal searches from the start again, so removing many matches from a long array is quadratic.

Parameters

array: *[] $T
item: T
$stop_after_first := false
removes only the first match.
$compare: (T, T) -> bool
decides whether two elements are equal. == when not given.

Returns

s64
ExampleOpen in playground ↗
values: [..] int;
array_add(*values, 1, 2, 1, 3, 1);
removed := array_unordered_remove_by_value(*values, 1);
assert(removed == 3 && values.count == 2);

once := array_unordered_remove_by_value(*values, 2, stop_after_first = true);
assert(once == 1 && values.count == 1 && values[0] == 3);
array_free(values);

See also