# How to prune from a list every element which doesn't share e.g. both its 1st and 2nd elements with SOME element in a specified other list?

This is a followup question to this one.

Let a and b be lists of lists like this:

a= {{"apples", "pears", 1, 17},
{"pineapples", "apples", 5, 7},
{"yes", "building", 4, 7},
{"no","camel","rabbit",0}}

b= {{"man", 1, 2, 17},
{"pineapples", "apples", "cow", "yes"},
{"no","camel","carpet","wibble"},
{"yes", "buildings", 4, 7}}


How can I remove from b every row that doesn't share both its 1st and its 2nd elements, say, in that order and in those specific slots, with any of the rows in a?

Once they've been deleted in this example, b would become

 b= { {"pineapples", "apples", "cow", "yes"},
{"no","camel","carpet","wibble"}}


As far as I can tell, ∈ can't be used to define a criterion in Cases.

• Maybe Select[b, ! FreeQ[a[[All, 1 ;; 2]], #[[1 ;; 2]]] &] Commented Oct 23, 2023 at 18:50
• Thanks, but that only picks up the "pineapples" element and misses the "no" one.
– tell
Commented Oct 23, 2023 at 19:24
• I guess that's because the comma is missing after the 3rd element in the definition of b Commented Oct 23, 2023 at 19:27
• Ah yes. You are right! It works fine now.
– tell
Commented Oct 23, 2023 at 19:28

Select[b, MemberQ[a[[All, {1, 2}]], #[[{1, 2}]]] &]

• Yes. Got it. This works fine now, as also does @vindobona's suggestion. Many thanks!
– tell
Commented Oct 23, 2023 at 19:29
Intersection[b, a, SameTest -> (#[[;; 2]] == #2[[;; 2]] &)]

{{"no", "camel", "carpet", "wibble"},
{"pineapples", "apples", "cow", "yes"}}

Cases[{a_, _} :> Flatten @ a] @
GatherBy[MapApply[{{#1, #2}, {##3}} &] @ Join[b, a], First]


{{"pineapples", "apples", "cow", "yes"}, {"no", "camel", "carpet", "wibble"}}

a = {{"apples", "pears", 1, 17}, {"pineapples", "apples", 5,
7}, {"yes", "building", 4, 7}, {"no", "camel", "rabbit", 0}}
b = {{"man", 1, 2, 17}, {"pineapples", "apples", "cow", "yes"}, {"no",
"camel", "carpet", "wibble"}, {"yes", "buildings", 4, 7}}

d1 = #[[1 ;; 2]] -> #[[3 ;;]] & /@ a;
d2 = #[[1 ;; 2]] -> #[[3 ;;]] & /@ b;

KeySelect[d2, KeyMemberQ[d1, #] &] // KeyValueMap[Flatten@*List]


{{"pineapples", "apples", "cow", "yes"}, {"no", "camel", "carpet",
"wibble"}}