[Question]
  [
Your challenge is to sort a string, but rather than by the normal alphabetical order (abc..xyz), you will be sorting strings by a specified alphabet.
You must write a program or function that takes two inputs: An alphabet **A** and an string **S**. Both will only contain lowercase English letters, and both will contain at least one character.
You must move letters in **S** so that the letter that appears first in **A** appears first, then whichever letter appears second in **A**, etc. There may be some letters in **S** that do not appear in **A**, these should be left at the end and not moved around relative to each other.
Test cases:
```
A       S               Result
axd     haxuizzxaxduxha aaaxxxxdhuizzuh
a       xyz             xyz
abc     dcba            abcd
il      nmiuplliu       iillnmupu
asdf    qwerty          qwerty
```
Fewest bytes wins!
  
[Answer]
# [Python 3](https://docs.python.org/3/), ~~50 47 46~~ 44 bytes
*-3 bytes thanks to ngn!*
*-1 byte thanks to mypetlion*
```
lambda a,s:s.sort(key=lambda c:a.find(c)%27)
```
[Try it online!](https://tio.run/##LYnLDsIgEEX3/Qo2BkhIF7owadIv0S7GUtKJlFYeceDnkaire885R47r7i7VjPdqYXtoYKDCEPqw@yieSx7/dh6gN@i0mOXpfJXV7J6RygwduwkOpLniK1DCUqhRohW4VK00T7l8P9oGbsN0WIvpl4M2Tb7ei4@Zy2noWBkthiiy7JgRpErbw6OLosj6AQ "Python 3 – Try It Online")
Takes in a string as the alphabet and a list of chars as the string and sorts the list in place.
The `%27` ensures that if the character is not in the alphabet, the index returned puts it after the rest of the alphabet.
[Answer]
## Haskell, 42 bytes
```
a#s=[c|c<-a,d<-s,c==d]++[c|c<-s,all(/=c)a]
```
[Try it online!](https://tio.run/##VcpBCsIwEIXhvacYpi6UpniBzkmkiyERMjiNxRiYBu8eW1x1@d73R87Ph2pr3GW6@68fB3ZhHLLzRGHq@/@XHatebuSvPLWZJQFBeJ0AlrekD5wBkC0gdICRrUittu1ikfEQiSLsUZqlLKpSjsyb7mxrxfYD "Haskell – Try It Online")
```
a#s=                     -- take alphabet a and string s
        c<-a             -- for all c in a
             d<-s        --   for all d in s
    [c|       c==d]             keep c if c equals d
   ++                    -- append
    [c|c<-s        ]     --   all c of s
         ,all(/=c)a      --   that are not in a 
```
[Answer]
# [Perl 6](https://perl6.org), ~~55~~ 43 bytes
```
->\A,\S{[~] S.comb.sort:{%(A.comb.antipairs){$_}//∞}}
```
[Try it](https://tio.run/##VU7LTsMwELz7K/YQUCNa99ZDo1bkzolwo6ja2q5i4SQmtqnbKJz5Cj6OHwnOQ6IdydLO7Mx4tajVqnNGwOeKsoSQ4gz3rOICNt1iu0vnu6x5/XqDjLKqOFBT1Xbd3M3SkWJppUZZm7iJ9u1y@fv907ZdqHi0wljYgJKlMNS8S00L1GtogJ6qmhv6JI2dQ7SHlpD@95fgT4hWWMLDEA6nHKt6KlpsYTaL0hDIwhNeC2YFj8PMhWExNARAGujv7m1RFl/ZJldC2i6FERnc4lkYpyxBzweao3fycvGBO58jIKIP4HmvupzgFPPny01N4AQPbJg5O@D1LuicSDWSspBOKyXdtJRSqbJw2hE0/NgrHydR2/N/fOR/ "Perl 6 – Try It Online")
```
->\A,\S{[~] S.comb.sort:{A.index($_)//∞}}
```
[Try it](https://tio.run/##VU7LboMwELz7K/aAKlAT55ZDUKJy76n01lSRsR1h1YCL7caA6Llf0Y/rj1DzkJKMtNLO7MzuKl7L7WA1h68tpjFCRQMPtGIc9sP6cExWx7R7@36HFNOqyLCuarPrEixKxl0YnKLN5u/nt@8HH3syXBvYgxQl11h/CIULonbQAb5UNdP4WWizguAEPULjxVfvj5GSpITHKezPn6t6WbQ@QBgGiQ@kvrhTnBrOIt8zrmkEHQIQGsZfR1uQRje2xRWjfkhgRgr3eOHaSoOIYxPNibOibZ3n1uUECCHOg@WjanNElphr2rs1niOS0alnNCO3M68zJORMykJYJaWwy1AIKcvCKouIZudR@bzw2jTX@Mz/AQ "Perl 6 – Try It Online")
## Expanded:
```
-> \A, \S {
  [~]  # reduce using &infix:«~» (shorter than `.join`)
    S.comb.sort: # split into character list and sort by:
      {  # bare block lambda with implicit parameter $_
        A.index( $_ ) # get the position
        //  # if it is undefined (not in `A`)
        ∞   # return Inf instead (so it comes at end of result)
      }
}
```
[Answer]
# [Haskell](https://www.haskell.org/), 40 34 bytes
**-6** bytes huge thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni).
```
foldr(\c->r(==c)<>r(/=c))
r=filter
```
[Try it online!](https://tio.run/##ZYsxD4IwFIR3fsVL4wADGBMHB3DRRBcTRweX2lJ58dFiKbHw463VUW65y313De8fNVHAtjPWwZ47XpyMNighTcttlkGeg9E0gjIWDscdlJtiXaySREEF16AMSZteRb61aVWJrIy@jJ4ltlJIrrah5ajjVpoEojqL2sECFLCG@wGnyXMvB99wBiwm9r/y4/Qls16K2@9yEzOkWxw6IhwiR5rh56u2bvx@e6lYeAtF/N6H/LI7nz8 "Haskell – Try It Online")
The first line is an expression that takes two arguments: **S** and **A**.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 bytes
```
{xrINo
```
[Run and debug it](https://staxlang.xyz/#c=%7BxrINo&i=%22axd%22+++++%22haxuizzxaxduxha%22&a=1)
This sorts by a block that does this.
* Reverse the alphabet.
* Get the index of each character in the reversed alphabet. Missing yields -1.
* Negate the index.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
Rvy†
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/qKzyUcOC//8TK1K4MhIrSjOrqiqA7NKKjEQA "05AB1E – Try It Online")
**Explanation**
```
R     # Reverse the alphabet
 vy   # For each letter ...
   †  # Push S with the current letter filtered to the front
```
[Answer]
# [Python 2](https://docs.python.org/2/), 38 bytes
```
def f(a,s):s.sort(None,a[::-1].find,1)
```
**a** must be a string, **s** a list of strings of length 1. **f** sorts **s** in place.
[Try it online!](https://tio.run/##NY6xCoMwFEVn/Yq3SAxEwUIpCB27Oth2Kh1iYzBgE@tLaPTnrYF0e@eey@VNix2MPmyb6CXInDOkNZZoZps3RveMP@q6qJ6lVFqwim7SzLC3ACkoDTnhXhAGZODeqXX1Ozo/cEJZcMH4ZY3UvQKLVxe1GgPrt3LTOCoXWyhkiD/ffrYLoXWaIJxhVGhzpGkyzUpbIFlxQsiK6ogEsvhQmsj/EVvt5XZvm@u@hzHbfg "Python 2 – Try It Online")
### Alternate version, string I/O, 48 bytes
```
lambda a,s:`sorted(s,None,a[::-1].find,1)`[2::5]
```
[Try it online!](https://tio.run/##LY5NCoMwGETX7Sm@jcRALChIIdAr9AJWMBqDAU1sfmj08qlBNwNv3ixm3dykVRUFvOATZ7b0nAEjlnZWGzfy3JK3ViNhDaVF2T6EVJyUuGsqSus2Cm0gZwQsBqkgRyxwRABNLHi57@FAHyaGMEkumbDtF/VDYj70l5ZzYrVIv86z9NfKcpHq7280bkOY3m@rkcoByoqnhawo6yMtguy8QUCcd3D8Aw "Python 2 – Try It Online")
### How it works
`s.sort(None,a[::-1],1)` is shorthand for `s.sort(cmp=None,key=a[::-1],reverse=1)`.
From [the docs](https://docs.python.org/2/library/functions.html#sorted):
> 
> *reverse* is a boolean value. If set to `True`, then the list elements are sorted as if each comparison were reversed.
> 
> 
> 
[Answer]
# [J](http://jsoftware.com/), 5 bytes
```
]/:i.
```
Dyadic verb, taking the alphabet on its left and the string to be sorted on the right.
`i.` finds the indeces of string's characters in the alphabet, the alphabet length if not found.
```
   'axd' i. 'haxuizzxaxduxha'
3 0 1 3 3 3 3 1 0 1 2 3 1 3 0
```
`/:` sorts its left agrument according to the order specified in the right one.
`]` the rigth argument (the string)
```
  'haxuizzxaxduxha' /: 3 0 1 3 3 3 3 1 0 1 2 3 1 3 0
aaaxxxxdhuizzuh
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Y/WtMvX@a3IpcKUmZ@QrqCdWpKgrpCmoZyRWlGZWVVUA@aUVGYnqMGmwZEVlFVwgKRkslJKcBFeUmQMWysvNLC3IyckshastTkkDyxSWpxaVVKr/BwA "J – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function, taking `[string,ordering]` as argument.
```
⍋⍨/⌷⊃
```
[Try it online!](https://tio.run/##ZYy9DsFQFMd3T3G3sxCDJxALk6T1AoerepOLojduu0oMtA2D0W4zmiwe5bxInbYkPv7DSc7/44eBbsgI9XyS55TuKb00KbnRbpN7tD1QmlF26vX5f1xbtD3y5zodvoNuz@XBWQjRFpVc8SdnvDI6rHmCkjuglcAe@GiNimPLv7E@gigwiGhZ0i8i41eT@uMCWG5sFMMXudiw@UYPR2VNjoYIvzUO5aundJnCbKpMoLUy8NFTSuvZ1ATmDV1Jj3NYrMfLMIJvaGU@AQ "APL (Dyalog Unicode) – Try It Online")
…`/` Reduce by the following function:
  …`⍨` namely the reversed-arguments version of the following function:
  `⍋` grade the right string according to the left ordering (missing letters go at the end)
`⌷` use that to index into…
`⊃` the first element of the argument (i.e. the string)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~35~~ 50 bytes
```
lambda a,s:sorted(s,key=lambda c:-a[::-1].find(c))
```
[Try it online!](https://tio.run/##LY1NCsMgGETX7SncqWAK7VJIL5Jm8UUjkRqT@EM1l7cR3M2bNzB7DstmX0X1n2JgnSQgYJ77zYVZEs@@c@5bL3gHA@fdc3wobSURlBa1ubpH2qKBYEgSM4QXSFGfZ7owpgUwZehy1aR8NppEZSmmprWpbFcdd2N0bCsvVa2P3@xCxnTk99vutA31k@H@jZkiV6TlDw "Python 2 – Try It Online")
Takes `a` and `s` as strings; returns a list of singelton strings.
Note: Ouch! Gained 15 bytes to fix...
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 9 bytes
```
{y@>-x?y}
```
[Try it online!](https://tio.run/##NYxBDoIwEEX3noI0LiARD0AT9RDsSBMGam1DKYg2TiF49doGnM3M///96XLzMN6LYnG3S45Xt/qyWI6V@06FSM4J0nroaFoLUJoidXTK2Hooq5QAckKJBLRqnjEoixJIRgkAYBguY2AlYRE/EQg0ujkScbHtSdMGm7fN1mxavgdKB9/0yo5aKxtDpbQ2vR3tv/riIjDPz316uwjsF/M/ "K (ngn/k) – Try It Online")
`{`...`}` is a function with arguments `x` and `y`
`x?y` finds for each element in `y` the index of its first occurrence in `x`; if an element is not found in `x`, its index is considered `0N` (-263)
`-` negates all indices except that it keeps the `0N`-s intact, because 263≡-263 (mod 264)
`>` returns a sort-descending permutation
`y@` indexes `y` with that
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
Ｆθ×ι№ηιΦη¬№θι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBo1BTIaAoM69EIyQzN7VYI1NHwTm/FMjN0FHI1NTUtOaCyLpl5pSkFoFE/fJLNCBKCiFKNK3//0@sSOHKSKwozayqqgCySysyEv/rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
 θ              First input
Ｆ               Loop over characters
     η          Second input
      ι         Current character
    №           Count matches
   ι            Current character
  ×             Repeat
                Implicitly print
        η       Second input
       Φ        Filter
           θ    First input
            ι   Current character
          №     Count matches
         ¬      Logical not
                Implicitly print non-matching characters
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
fⱮ;ḟ
```
A dyadic link accepting the string on the left and the alphabet on the right (as lists of characters) and returning the result (also as a list of characters).
**[Try it online!](https://tio.run/##y0rNyan8/z/t0cZ11g93zP///39GYkVpZlVVRWJFSmlFRuJ/IA0A "Jelly – Try It Online")**
### How?
```
fⱮ;ḟ - Link: string; alphabet                                    e.g. smallnotxl; xl
 Ɱ   - map (for each character in the alphabet):                      1=x; 2=l
f    -   filter keep (keep occurrences of this character from string)   x    lll -> xlll
   ḟ - filter discard (discard all alphabet characters from string)   smanot
  ;  - concatenate                                                    xlllsmanot
```
[Answer]
# JavaScript (SpiderMonkey), 50 bytes
Takes input in currying syntax `(a)(s)`, where **a** is a string and **s** is an array of characters. Returns an array of characters.
```
a=>s=>s.sort((b,c)=>(g=c=>-1/a.search(c))(b)-g(c))
```
[Try it online!](https://tio.run/##fU7NcoQgDL73KZhcFmYqTh9AX6TTQwQUtggWpEVf3uLs1oPbNpNDku8n3xU/MYpgprmKk5EqjN69q2Xrmw2bNpbm0YeZ0u5ZsKalQyOatnqpkUeFQWgqGKMdq4Z92IR30VvFrR9oTwGzBMLoK@ccNOZk1jWXW8oa4Y3xqzeOXi6MkbomiJhLSb2zkn46WwEhP1Z5WfftqLNVwR/knTiSSNEh/CMvXHnWGwvHezeaNFlrEvyuN8ZaN6YpPYSIsoe7yceXCvMCf4a44ds3 "JavaScript (SpiderMonkey) – Try It Online")
### How?
We define the helper function **g()** as:
```
c => -1 / a.search(c)
```
which returns:
* **1** if **c** does not belong to the alphabet
* a float value in **[-Inf, 0)** based on the position of **c** in the alphabet otherwise (-Inf, -1, -1/2, -1/3, etc.)
We sort **s[ ]** by computing **g(b) - g(c)** for each pair of characters **(b, c)** passed to the callback of **sort()**.
Because the implementation of **sort()** in SpiderMonkey is stable, all characters of **s[ ]** that do not belong to the alphabet are simply moved at the end in order of appearance and are let unchanged when they are compared with each other.
---
# JavaScript (ES6), 61 bytes
Takes input in currying syntax `(a)(s)`, where both **a** and **s** are arrays of characters. Returns a string.
```
a=>s=>a.map(C=>s=s.filter(c=>c!=C||!(o+=c)),o='')&&o+s.join``
```
[Try it online!](https://tio.run/##bU7LjsIwDLzvVwQfIBEQviC98BkrJEzSUqM06TbNbqj499KKl2A7J8/YM@MT/mLQDdXt2nmT94XqUWVBZSgrrPl2nIMsyLZ5w7XK9ExtL5cZ90ulhVh5tViI@dwvgzx5cvt9r70L3ubS@iMv@LeUEjAZYDtxIyWmSF2XBjGmEmEnBNtsGCKmAaYcl7H8mooBxp4x6dyN9Il7zCBPWg/69YHRB4T/1uHGTHnJwqvWVRRraynCm5fIWlfFOk6WB1PAI@DnL2/aM3yW3@T@Cg "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~69 62~~ 58 bytes
```
function(a,s)c(rep(a,rowSums(outer(a,s,"=="))),s[!s%in%a])
```
[Try it online!](https://tio.run/##XYvBbsMgEETv@Yp2o0gg8Qt8RY5VDxjseCWMKcsq2D/vLI5UVd3L7MybKcdkj4mTr7gm5Qxpr8qY5Svr884LqZXrWDoxYC1orQ19fdIN08196@Nhf8fNbNq7qibFKSJVRbVQjliFnGpB5uY/3P5AbeAChsbc3eWhwLUABmbXGPe9ieM2O9DXD@dckwtzBzyfXWm2be9U5EwGL1nww3sy@NBTjBKmBTnHiNwJYoxp4czniMIkhZ/nWOrW6fs7Xg "R – Try It Online")
Input and output are vectors of individual characters.
Explanation:
```
function(a,s)c(                              ,           ) #combine:
                   a,                                      #[each char in a
               rep(                                        #each repeated
                     rowSums(               )              #the number of
                             outer(a,s,"==")               #occurrence in s]
                                              s            #with s
                                               [ s%in%a]   #all chars in a
                                                !          #omitted
```
[Answer]
# [Brain-Flak (BrainHack)](https://github.com/Flakheads/BrainHack), 118 bytes
```
{({}(<>))<>}{}<>{<>([[]()]<{<>(({})<({}<>[({}<>)]){(<()>)}{}{}>)<>}<>({}<{({}<>)<>}<>>)>[]){({}()<(({}))>)}{}{}<>{}}<>
```
[Try it online!](https://tio.run/##NY0xCkJBDETvslWmEDxACHiOZYuoxX4EC@HD8kPOHpMvNkOGNzO5f3R7T328IozMiQVgcXMWY6HeB2FwnUnBVKCfigEjJggybS5Vy1gi@/HTC6RXMKezXRv/Qj7wlIi43KLpera4Rpu69u04Vvp9TW1f "Brain-Flak (BrainHack) – Try It Online")
Input is the first string, followed by a null, followed by the second string. A version that uses a newline as the separator instead adds 24 bytes:
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 142 bytes
```
(()){{}(({}(<>))[(()()()()()){}]<>)}{}<>{<>([[]()]<{<>(({})<({}<>[({}<>)]){(<()>)}{}{}>)<>}<>({}<{({}<>)<>}<>>)>[]){({}()<(({}))>)}{}{}<>{}}<>
```
[Try it online!](https://tio.run/##NU1BCsNACLz3Jc4hPxA/suzBtpSElB4KgSXi261uCaKMM6Nz/@r2WV5v3SOIADMnymYBWhJXwbwn5@YsxkKtdULngmkHUwltTnQYMWG6zQUsyZZkf33uAmllzKy8rh/XQQZ4jggdz9uq49jOcyQ@xqqxPH4 "Brain-Flak – Try It Online")
### Explanation
```
# Move A to other stack reversed
# Zeroes are pushed under each character for later.
# (This is the only part that needs to change in order to use newline as separator.)
{({}(<>))<>}{}<>
# For each character in A, starting at the end:
{
  # Track current length of S.
  <>([[]()]<
    # For each character in S:
    {
      # While keeping character from A
      <>(({})<
        # Move character from S to second stack and push difference
        ({}<>[({}<>)])
        # Delete character if equal
        {(<()>)}{}{}
      >)
    <>}
    # Move S back to first stack while maintaining character from A
    <>({}<{({}<>)<>}<>>)
  # Push difference between old and new lengths of S
  >[])
  # Insert character from A at beginning of S that many times
  {({}()<(({}))>)}{}{}
<>{}}<>
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 97 bytes
```
f(D,d,S,s,i,o)char*D,*S;{
  while(d--){
    for(i=o=s;i--;)S[i]-D[d]?S[--o]=S[i]:0;
    while(o--)S[o]=D[d];
  }
}
```
All whitespaces (spaces and newlines) in the code above are only for readability and should be removed.
The dictionary is passed in `D` and have length `d`, the string is passed in `S` and have length `s`. `i` and `o` should be omitted.
[Try it online!](https://tio.run/##PU3LboMwELzzFStXFXZkV@21Du2FP@DocrBsqFdKcIRBtUB8O12SqnNY7c5jx6lv5/a957X0spFJoozCBTueanlq9PoT8NJxr5RY@zhyrGKVNCqlRWOwVbXx7WdjlIptdRDvr/qRiJRoDLGHQ2/b/oSDu8y@g3OaPMaX8FEcNWBNCxWspS0llPkYvtz0Q0t3jQWbZ1yWbLOfc7BMFzhMcLU4cAFrAYSeWwkJly7SJmj9v5IABW9C3223eUrE/B0jvek5e/ZfAyP/NLrrjVOSWWszwYejdg5MUGLbfwE "C (gcc) – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~9~~ 5 bytes
```
ox+vz
```
[Try it here!](https://pyth.herokuapp.com/?code=%2Bs%40RQKE-K&input=%22axd%22%0A%22haxuizzxaxduxha%22&debug=0)
```
ox+vz    Full program. Input format: "S" \n "A".
o        Sort the characters of S by (variable: N)...
 x       ... N's index in...
  +vz    ... A + N
```
[Answer]
# Java 8, 98 bytes
```
a->s->{for(int i=a.length;i-->0;s=s.replaceAll("[^"+a[i]+"]","")+s.replaceAll(a[i],""));return s;}
```
[Try it online.](https://tio.run/##jY/NasMwEITveYpFJ5vEonc3hl566ynHkMLGP8kmG1m1Vqmd4Gd3ZZocCoYaBBL7aWZnTnjF5FSch5zROfhAMvcFgBMUyuEUqPZCrCtvcqHa6PfH43UjDZnDdrea8WsFv3eWQQXrAZPMJdm9qpuIjACtUXNpDnJMKUmyl9StnW5Ky5iXb8yR2n6qJW5pt1Q7tVIqXv7BIxmncdqU4hsDLu2HNJQIx/o9hx6POteaCriEitEzPGA81gXYdE7Ki669aBuQsIkqjdZyFylsC6WdZZJoXPMcH7H1dLu1Afv2iGOA/62mjNruNk@8z6fkRb6ft5x4Sm4u5C0z@XkZXFFNuXx9l410D4t@0Q8/)
**Explanation:**
```
a->s->{       // Method with String-array and String parameters, and String return-type
  for(int i=a.length;i-->0;
              //  Loop backwards over the alphabet
    s=        //   Replace the current `s` with:
      s.replaceAll("[^"+a[i]+"]","") 
              //    All the current characters of `a` in `s`
      +s.replaceAll(a[i],""));
              //    Concatted with everything else
  return s;}  //  Return the modified `s`
```
[Answer]
## [Perl 5](https://www.perl.org/) with `-pF`, 43 bytes
```
$_=<>;print$F[0]x s/@{[shift@F]}//g while@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tbGzrqgKDOvRMUt2iC2QqFY36E6ujgjM63EwS22Vl8/XaE8IzMn1cHt///EihSujMSK0syqqgogu7QiI/FffkFJZn5e8X/dAjcA "Perl 5 – Try It Online")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 136 bytes
```
X/_/[X|_].
X/Y/[Z|R]:-Y\=Z,X/Y/R.
i(_,X,[],[X]).
i(A,X,[Y|R],[X,Y|R]):-X/Y/A.
i(A,X,[Y|R],[Y|S]):-i(A,X,R,S).
A*S*T:-foldl(i(A),S,[],T).
```
[Try it online!](https://tio.run/##XYzBCoMwEETvfkUvgsok3oUe/AXjIZoGEaQ1kKq0hIr473a33rp72H07M7u8Zj8/xPvjjkPnXW703lkZ6bzJTbtXthDN7dqCuZKRSzpoGAujbcpYMjbkowt4poVgb/knNrti6bxVUBQuM5XVhbjPfvAJCSkUf65TeRyx6bFisJkZwVuAw0a9/mggXkGKzZS8xH3fr1TDGNy2hTEyDp6SE56UCljgqWk73c55Pz3DEr4 "Prolog (SWI) – Try It Online") Example usage:
```
[i,l]*[n,m,i,u,p,l,l,i,u]*S.
S = [i, i, l, l, n, m, u, p, u]
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 61 bytes
```
import StdEnv
$a s=[c\\c<-a,k<-s|k==c]++[c\\c<-s|all((<>)c)a]
```
[Try it online!](https://tio.run/##RYzLDoIwFET3fEUTSYAgf0Bd6cLEHUtgcb28GvogtDWV8O1WgkaXc87MIG9BeqEay1sigEnPxKRmQwrTXOQjCIFoWmJVYZ7BccwzvY6UYp2mX6hX4DyO81OCCdS@MDCb4ECATwPcW0MoKSNwTVRvUJuZyX5HAzjLlsVtyroBdt1ZiYYpuRXCgP7j7@uz9y/sOPTaZ9ebPz8lCIb6DQ "Clean – Try It Online")
Defines the function `$ :: [Char] [Char] -> [Char]`.
Unsurprisingly, this is literally [nimi's Haskell answer](https://codegolf.stackexchange.com/a/165488/18730) but longer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
i@oİ$¥Þ
```
[Try it online!](https://tio.run/##y0rNyan8/z/TIf/IBpVDSw/P@///f2JSctX/xOQkAA "Jelly – Try It Online")
[Answer]
# APL+WIN, 12 bytes
Prompts for screen input of S then A:
```
s[(,⎕)⍋s←,⎕]
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4XR2voAIU0H/V2FwNFQezY/0CZ/2lc6hmJFaWZVVUViRUppRUZiepc6kCWOgA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [PynTree](https://github.com/alexander-liao/pyn-tree), 13 bytes
```
§yz:ṡzCæf+yxx
```
[Try it online!](https://tio.run/##K6jM0y0pSk39H@CV/P/Q8soqq4c7F1Y5H16Wpl1ZUfE/mkspsSJFiUspI7GiNLOqqgLIK63ISFTiiv0PAA "PynTree – Try It Online")
Port of Jo King's Python answer.
# Explanation
```
§yz:ṡzCæf+yxx  Anonymous lambda
§              lambda  ,
 y                    y
  z                     z
   :                     :
    ṡ                     sorted( ,lambda x:
     z                           z
      C                                     (          )( )
       æf                                    (   ).find
         +                                     +
          y                                   y
           x                                    x
            x                                            x
```
]