I am trying to find a nice and clean method to select elements from one list which are in another list or the criteria is based on another list. The ones I want to returned are in listA
and the ones that contain the matching criteria are in listB
. listA
has different dimensions than listB
and I only apply the criterion on certain subset say, listA[[All,1]]
. Obviously, not all elements in listA[[All,1]]
have to be present in listB
and not all elements of listB
are present in listA[[All,1]]
So far, I have come up with the two almost identical methods:
listA = {{"a", 1, 3}, {"b", 3, 4}, {"e", 4, 4}, {"r", 2, 2}}
listB = {"a", "c", "d", "e"}
Function[u, Select[listA, #[[1]] == u &]] /@
Intersection[listA[[All, 1]], listB]
Function[u, Select[listA, #[[1]] == u &]] /@ listB
Obviously the second one returns also empty sublists which need to be deleted. Both suffer from producing an additional dimension {{{"a", 1, 3}}, {{"e", 4, 4}}}
which, of cource, can be corrected with flatten. But, I am interested if there is another, a more elegant way, that would keep the structure of listA
, without having to figure out at which level to flatten (it is simple in the example above)? (to summarize, I already have a working solution, i am just interesting in other or better ways to do it which I am missing, thank you)
ToAssoication
would be worth trying. $\endgroup$