# Truncate a set of lists until a subset of entries matches?

Consider lists of vectors of elements like

list[1]={{a1,b1,c11},{a2,b2,c12},{a3,b3,c13},{a4,b4,c14},{a5,b5,c15}};
list[2]={{a1,b1,c21}            ,{a3,b3,c23},{a4,b4,c24},{a5,b5,c25}};
list[3]={{a1,b1,c31},{a2,b2,c32},{a3,b3,c33}            ,{a5,b5,c35}};


where the length 3 of vectors in lists is just an example and could be longer, and there may be more than 3 such lists.

I would like to have a function truncate[listoflists_] that takes all these lists and truncates them to only have the vectors containing ai,bi entries that are present in all of them:

{list[1],list[2],list[3]}=truncate[{list[1],list[2],list[3]}];
list[1]
list[2]
list[3]


{{a1,b1,c11},{a3,b3,c13},{a5,b5,c15}}

{{a1,b1,c21},{a3,b3,c23},{a5,b5,c25}}

{{a1,b1,c31},{a3,b3,c33},{a5,b5,c35}}

Is there a quick way to do this in Mathematica? Thanks for any suggestion.

It is short (does not mean quick) to get it via associations:

truncate = Values @ KeyIntersection @ Map[#[[;; 2]] -> # &, #, {2}] &


We convert {a1,b1,c11} to {a1,b1}->{a1,b1,c11} and everything else is straightforward.

• Love it when a mod ends up in the LQ review. :) Nov 23, 2018 at 21:45
– Kuba
Nov 23, 2018 at 21:53
• I approved it anyway. It's not always clear that excessive exposition would be an improvement. Nov 23, 2018 at 22:00
• I have changed it to truncate = Values@KeyIntersection@Map[{#[[1]], #[[2]]} -> # &, #, {2}] & to make it compatible with longer vector cases. Nov 23, 2018 at 23:35
• @Kagaratsch right, you mentioned it. I edited the code.
– Kuba
Nov 24, 2018 at 0:27

Also

tF = Module[{i = Intersection@@#[[;;, ;;, #2]], k = #2}, Select[MemberQ[i, #[[k]]]&]/@ #]&

lists = list /@ {1, 2, 3};
tF[lists, {1, 2}]


{{{a1, b1, c11}, {a3, b3, c13}, {a5, b5, c15}},
{{a1, b1, c21}, {a3, b3, c23}, {a5, b5, c25}},
{{a1, b1, c31}, {a3, b3, c33}, {a5, b5, c35}}}