# Subtract more than one array using DeleteCases

I need to create an array subtracting two arrays from another array. I know how to subtract one:

am = DeleteCases[amp, Alternatives @@ af]


I can subtract an array each time but there must be a way to subtract more than one array at once. So I want to subtract af and ai from amp. How can I do that at once?

You can use Select as well :

ar = Range[10];
ar1 = Range[1, 10, 2];
ar2 = Range[1, 10, 3];

Select[ar, Not[MemberQ[Union[ar1, ar2], #]] &]
(* {2, 6, 8} *)

DeleteCases[ar, _?(MemberQ[Union[ar1, ar2], #] &)]
(* {2, 6, 8} *)

• Or, DeleteCases[ar, Alternatives @@ Union[ar1, ar2]].
– VLC
Commented Feb 25, 2013 at 10:26
• Not@MemberQ is equivalent to FreeQ. Commented Mar 11, 2013 at 11:18

The built-in function Complement does exactly what you need:

With

ar = Range[10];
ar1 = Range[1, 10, 2];
ar2 = Range[1, 10, 3];


elements in the first list that are not in any of the subsequent lists are:

Complement[ar, ar1,ar2]
(* {2, 6, 8 *)

a = {9, 4, 7, 1, 5, 3, 8, 5, 7, 3, 1, 0};
b = {7, 5};
c = {8, 3};


DeleteElements (new in 13.1) keeps duplicates and is equal with the accepted answer

DeleteElements[a, Join[b, c]]


{9, 4, 1, 1, 0}

UniqueElements (also new in 13.1) deletes duplicates

Join @@ UniqueElements[{a, b, c}]


{9, 4, 1, 0}

kglr's solution sorts the elements and deletes duplicates

Complement[a, b, c]


{0, 1, 4, 9}

The accepted answer doesn't sort and keeps duplicates

Select[a, Not[MemberQ[Union[b, c], #]] &]


{9, 4, 1, 1, 0}

Using eldo's data:

a = {9, 4, 7, 1, 5, 3, 8, 5, 7, 3, 1, 0};
b = {7, 5};
c = {8, 3};


An alternative is to use ReplaceAll:

a /. Thread[Join[b, c] -> Nothing]

(*{9, 4, 1, 1, 0}*)


Grabbing the data from @eldo we can use UniqueElements which was introduced in v13.1

a = {9, 4, 7, 1, 5, 3, 8, 5, 7, 3, 1, 0};
b = {7, 5};
c = {8, 3};
Flatten[UniqueElements[{a, b, c}]]


{9, 4, 1, 0}

a = {9, 4, 7, 1, 5, 3, 8, 5, 7, 3, 1, 0};
b = {7, 5};
c = {8, 3};


Using Pick and FreeQ

Pick[a, FreeQ[Union[b, c], #] & /@ a]


{9, 4, 1, 1, 0}

Grabbing @eldo's data:

a = {9, 4, 7, 1, 5, 3, 8, 5, 7, 3, 1, 0};
b = {7, 5};
c = {8, 3};


Another way using Position and Delete:

Delete[a, Position[a, Alternatives @@ Join @@ {b, c}]]


{9, 4, 1, 1, 0}