# Selecting list elements depending if they contain sub-list elements

I have:

aa = {{1, 1}, {2, 2}}

bb = {{4, 4}, {5, 5}}

cc = {{a, {1, 1}}, {b, {2, 2}}, {c, {3, 3}}, {d, {4, 4}}, {e, {5, 5}}, {f, {6, 6}}}


How can I select all elements form cc that contain all elements from aa as well as from bb?

The result should be:

{{a, {1, 1}}, {b, {2, 2}}, {d, {4, 4}}, {e, {5, 5}}}

• ... if you've already assigned values to a and b, they will not show up in c. – J. M. is in limbo Sep 13 '17 at 16:34
• sorry for the mistake ... – mrz Sep 13 '17 at 18:11

You may use ContainsAny.

Select[cc, ContainsAny[Join[aa, bb]]]

{{a, {1, 1}}, {b, {2, 2}}, {d, {4, 4}}, {e, {5, 5}}}


Hope this helps.

aa = {{1, 1}, {2, 2}};
bb = {{4, 4}, {5, 5}};
cc = {{a, {1, 1}}, {b, {2, 2}}, {c, {3, 3}}, {d, {4, 4}}, {e, {5, 5}}, {f, {6, 6}}};


Then,

Cases[cc, {_, Alternatives @@ Join[aa, bb]}, {1}]
(* {{a, {1, 1}}, {b, {2, 2}}, {d, {4, 4}}, {e, {5, 5}}} *)


Several methods in addition to Cases in @march's answer:

Select[cc, MemberQ[Join[aa, bb], #[[2]]] &]
Pick[cc,  MemberQ[Join[aa, bb], #[[2]]] & /@ cc]
DeleteCases[cc, _?(! MemberQ[Join[aa, bb], #[[2]]] &)]


{{a, {1, 1}}, {b, {2, 2}}, {d, {4, 4}}, {e, {5, 5}}}

Select[cc, MemberQ[Join @@ Thread[aa | bb]]]

{{a, {1, 1}}, {b, {2, 2}}, {d, {4, 4}}, {e, {5, 5}}}

• Also ContainsAny[Join[aa, bb]]. – Edmund Sep 13 '17 at 23:31
• @Edmund Nice, but unfortunately not available in version 10.1 which I use. – Mr.Wizard Sep 13 '17 at 23:39
• Can't you offer WRI some rep for an upgrade? – Edmund Sep 13 '17 at 23:41

It is also possible by using rules:

cc /. {s_Symbol, pair_List} /; !MemberQ[Join[aa, bb], pair] -> Nothing