I have two lists, which as a simple example can take the form:

l1 = {{a1,a2,a3},{b1,b2,b3},{c1,c2,c3}}
l2 = {{a1,n1},{c1,n2}}

How can I merge them by the first element in the list to obtain a list of the form

newList = {{a1,a2,a3,n1},{c1,c2,c3,n2}}.

I tried


but this will only return the last elements of each (e.g. {{a1,a3,n1},{c1,c3,n2}, how do I keep all the elements? Thanks.

l1 = {{a1, a2, a3}, {b1, b2, b3}, {c1, c2, c3}};
l2 = {{a1, n1}, {c1, n2}};

l3 = {{a1, n1}, {c1, n2}, {a1, n3}};

merge[l1_List, l2_List] := 
 Join[#[[1]], Rest[##][[All, -1]]] & /@
  Select[GatherBy[Join[l1, l2], First], Length[#] > 1 &]

merge[l1, l2]

(* {{a1, a2, a3, n1}, {c1, c2, c3, n2}} *)

merge[l1, l3]

(* {{a1, a2, a3, n1, n3}, {c1, c2, c3, n2}} *)
| improve this answer | |
  • $\begingroup$ Question: Why do you overwrite l2 in the third line of the answer? $\endgroup$ – PaulCommentary Jul 24 at 17:07
  • 1
    $\begingroup$ @PaulCommentary - when I added the second example I wasn't paying attention. Corrected my error. Thanks. $\endgroup$ – Bob Hanlon Jul 24 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.