# List rearrangment with joining of strings

I have a list of strings:

lis = {{"a","b","x"},{"d","e","y"},{"a","b","z"},{"d","c","x"},{"a","b","w"}}


I would like to use StringJoin on the last elements where initial elements are the same to obtain:

res = {{"a","b","xzw"},{"d","e","y"},{"d","c","x"}}


Doing:

lis = SortBy[lis, {#[[1]]} &]
SequenceCases[lis, {{a_, b_, c_}, {a_, b_, d_}} :> {a, b, StringJoin[c, d]}]


only gives:

{{"a", "b", "wx"}}


Thanks for any suggestions.

• At least closely related: mathematica.stackexchange.com/q/26574/5478 – Kuba Sep 27 '18 at 19:04
• @Suite401, do you have control on how the "initials" are generated? If they where integers (which can be achieved with ToCharacterCode), then I could also image faster methods. – Henrik Schumacher Sep 27 '18 at 19:43
• @Henrik, Each actual element of the list looks like: {DateObject,String,String representation of integer,String,String representation of integer,String,String,String} so I'm not sure there's much to be done, but am interested in your thoughts. – Suite401 Sep 27 '18 at 19:53
• Okay, my idea would have required that the number of keys is known a priorily. Btw., I found out that Carl Woll's code is much faster than mine. – Henrik Schumacher Sep 27 '18 at 19:58

Another variation:

KeyValueMap[Append] @ GroupBy[lis, Most->Last, StringJoin]


{{"a", "b", "xzw"}, {"d", "e", "y"}, {"d", "c", "x"}}

although you may like just the output of GroupBy[lis, Most->Last, StringJoin] better.

KeyValueMap[
{key, value} \[Function] Join[key, {StringJoin[value]}],
GroupBy[lis, Part[#, 1 ;; 2] & -> Last]
]


{{"a", "b", "xzw"}, {"d", "e", "y"}, {"d", "c", "x"}}

• That's probably the first time I've seen anyone use the infix function notation here. I forgot that even existed. – Sjoerd Smit Sep 27 '18 at 20:18
• @Sjoerd Actually, I use it quite often... – Henrik Schumacher Sep 27 '18 at 20:19

Another one:

 KeyValueMap[Append] @ Merge[StringJoin][ {#, #2} -> #3 & @@@ lis ]

• Thanks Henrik, Kuba; am checking to see which is faster on big data set – Suite401 Sep 27 '18 at 19:06