Having for example this list
list = [1, 2, 3, 4, 4]
I can filter out the elements which are equal to 4 like this.
Enum.reject(list, fn item -> item == 4 end)
Is there any way to obtain the rejected items? like [4, 4]
Something like:
rejected = Enum.get_rejected(list, fn item -> item == 4 end)
more_rejected = Enum.get_rejected(list, fn item -> item == 3 end)
remaining = list
I can achieve that right now iterating several times, like:
rejected = Enum.filter(list, fn item -> item == 4 end)
more_rejected = Enum.filter(list, fn item -> item == 3 end)
remaining = Enum.reject(list, fn item -> item != 4 and item != 3 end)
You can use Enum.split_with/2 to get a tuple of filtered and rejected lists:
iex(1)> list = [1, 2, 3, 4, 4]
[1, 2, 3, 4, 4]
iex(2)> {accepted, rejected} = Enum.split_with(list, fn item -> item == 4 end)
{[4, 4], [1, 2, 3]}
iex(3)> {more_accepted, remaining} = Enum.split_with(rejected, fn item -> item == 3 end)
{[3], [1, 2]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With