Sort a string by a given ordering

Python 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!

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.

Haskell, 42 bytes


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 

Perl 6,  55  43 bytes

->\A,\S{[~] S.comb.sort:{%(A.comb.antipairs){$_}//∞}}

Try it

->\A,\S{[~] S.comb.sort:{A.index($_)//∞}}

Try it


-> \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)