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.


3 Answers 3

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}} *)
  • $\begingroup$ Question: Why do you overwrite l2 in the third line of the answer? $\endgroup$ Jul 24, 2020 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, 2020 at 17:13
a = {{a1, a2, a3}, {b1, b2, b3}, {c1, c2, c3}};

b = {{a1, n1}, {c1, n2}};

KeyValueMap[Flatten @* List] @
 KeyTake[First /@ b] @ GroupBy[Join[a, b], First -> Rest]

{{a1, a2, a3, n1}, {c1, c2, c3, n2}}

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

l2 = {{a1, n1}, {c1, n2}};

Using SortBy and SplitBy:

Cases[s : {_, _} :> Union @@ s]@SplitBy[SortBy[Join[l1, l2], First], First]

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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