[Question]
  [
# Challenge description
You have a music library with many tracks recorded by many bands, each of which has a name, like `Queen`, `Aerosmith`, `Sunny Day Real Estate`, `The Strokes` . When an audio player displays your library alphabetically by band name, it usually skips the `The` part, as many band names start with `The`, making it easier to navigate through your media collection. In this challenge, given a list (array) of strings, you need to sort it that way (that is, omitting the `The` word at the beginning of the name). You can either write a method or a full working program.
# Sample inputs / outputs
```
[Queen, Aerosmith, Sunny Day Real Estate, The Strokes] -> [Aerosmith, Queen, The Strokes, Sunny Day Real Estate]
[The Ramones, The Cure, The Pixies, The Roots, The Animals, Enrique Iglesias] -> [The Animals, The Cure, Enrique Iglesias, The Pixies, The Ramones, The Roots]
[The The, The They, Thermodynamics] -> [The The, Thermodynamics, The They]
```
# Notes / Edge cases
* Sorting lexicographically is case insensitive, so `The Police`, `The police` and `the police` are all equivalent,
* Your algorithm should only omit the first `the` word, so bands named `The The` or `The The Band` are sorted normally by the second `the`,
* A band named `The` (a three letter word) is sorted normally (no skipping),
* Order of two bands having the same name, one of which starts with `the` (like `The Police` and `Police`) is undefined,
* You can assume that if a band's name consists of more than one word, they are separated by a single space character. You don't need to handle leading or trailing whitespaces,
* All input strings match `[A-Za-z0-9 ]*`, that is they will consist only of lower- and uppercase letters of English alphabet, digits and space characters,
* Remember that this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so make your code as short as possible!
  
[Answer]
## Python, ~~56~~ ~~62~~ 64 bytes
```
lambda b:sorted(b,key=lambda x:(x,x[4:])[x.lower()[:4]=='the '])
```
[Try it](https://repl.it/CilL/1)
Thanks to @Chris H for pointing out that `lstrip()` was not handling `The The` correctly, since the strip was blasting all matching characters and sorting it as a blank string, and @manatwork for finding the flaw in using `replace()`. The new version should work.
Old version:
```
lambda b:sorted(b,key=lambda x:x.lower().lstrip('the '))
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~32~~ 28 bytes
```
ç^The /dwA_
:sort
ç_/$xIThe 
```
[Try it online!](http://v.tryitonline.net/#code=w6deVGhlIC9kd0FfCjpzb3J0CsOnXy8keElUaGUg&input=VGhlIFJhbW9uZXMKUmFkaW9oZWFkClRoZSBDdXJlClRoZSBQaXhpZXMKVGhlIFJvb3RzClRoZSBBbmltYWxzCkVucmlxdWUgSWdsZXNpYXM)
*Note to self: Make an abbreviation for `:sort` so that I don't need 6 whole bytes for a single command!*
Explanation:
```
ç^The /     "On every line starting with 'The ',
       dw   "Delete a word
         A_ "And (A)ppend an underscore '_'
:sort       "Sort all lines alphabetically
ç_/         "On every line containing an underscore,
   $x       "Delete the last character
     IThe   "And prepened 'The '
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 34 bytes
The trailing linefeed is significant.
```
%`^
$';
T`L`l`.+;
m`^the 
O`
.+;
```
I/O is one band per line.
[Try it online!](http://retina.tryitonline.net/#code=JWBeCiQnOwpUYExgbGAuKzsKbWBedGhlIAoKT2AKLis7Cg&input=UXVlZW4KQWVyb3NtaXRoClN1bm55IERheSBSZWFsIEVzdGF0ZQpUaGUgU3Ryb2tlcwpUaGUgUmFtb25lcwpUaGUgQ3VyZQpUaGUgUGl4aWVzClRoZSBSb290cwpUaGUgQW5pbWFscwpFbnJpcXVlIElnbGVzaWFzClRoZSBUaGUKVGhlIFRoZXkKVGhlcm1vZHluYW1pY3M)
### Explanation
```
%`^
$';
```
Duplicate each line, using `;` as a separator.
```
T`L`l`.+;
```
Turn everything in front of a `;` to lower case.
```
m`^the 
```
Remove any `the`s that appear at the beginning of a line.
```
O`
```
Sort the lines.
```
.+;
```
Remove the beginnings of the lines which we used for sorting.
[Answer]
## Pyke, 16 bytes
```
.#l1D"the ".^4*>
```
[Try it here!](http://pyke.catbus.co.uk/?code=.%23l1D%22the+%22.%5E4%2a%3E&input=%5B%22Queen%22%2C+%22Aerosmith%22%2C+%22Sunny+Day+Real+Estate%22%2C+%22The+Strokes%22%5D)
```
.#                - sort_by(V, input)
  l1              -  i = i.lower()
      "the ".^    -   i.startswith("the ")
              I   -  if ^:
               4> -   i[4:]
```
[Answer]
# Perl, 52 bytes
*-13 byte thanks to @manatwork*  
*-1 byte thanks to @msh210*
```
sub f{lc pop=~s/^the //ri}print sort{f($a)cmp f$b}<>
```
One band per line as input, and so is the output.
The implementation is quite straight forward : the program prints the list of bands, sorted with the help of a custom function (`f`) which returns the lower case band name without the eventual leading `the` .
[Answer]
# Python, ~~66~~ ~~72~~ 69 bytes
```
lambda x:sorted(x,key=lambda a:a[4*(a.lower()[:4]=='the '):].lower())
```
Uses Python's `sorted` method with the `key` keyword argument to sort by the name minus "The". This is a lambda; to call it, give it a name by putting `f=` in front.
Now with extra case insensitivity!
[Answer]
# Ruby, 42 bytes
```
->a{a.sort_by{|s|s.upcase.sub /^THE /,''}}
```
[Try it online!](https://repl.it/Ciq3)
[Answer]
# [Perl 6](http://perl6.org), 26 bytes
```
*.sort({fc S:i/^'the '//})
```
### Explanation:
```
# ｢*｣ is the input to this Whatever lambda
*.sort(
  # sort based on the return value of this Block lambda
  {
    fc # foldcase the following
    # string replace but not in-place
    S
      :ignorecase
      /
        # at the start of the string
        ^
        # match ｢the ｣
        'the '
      # replace with nothing
      //
  }
)
```
### Test:
```
use v6.c;
use Test;
my @tests = (
  « Queen Aerosmith 'Sunny Day Real Estate' 'The Strokes' »
    => « Aerosmith Queen 'The Strokes' 'Sunny Day Real Estate' »,
  « 'The Ramones' 'The Cure' 'The Pixies' 'The Roots' 'The Animals' 'Enrique Iglesias' »
    => « 'The Animals' 'The Cure' 'Enrique Iglesias' 'The Pixies' 'The Ramones' 'The Roots' »,
  « 'The The' 'The They' Thermodynamics »
    => « 'The The' Thermodynamics 'The They' »,
);
# give it a lexical name for clarity
my &band-sort = *.sort({fc S:i/^'the '//});
plan +@tests;
for @tests -> ( :key(@input), :value(@expected) ) {
  is-deeply band-sort(@input), @expected, @expected.perl;
}
```
```
1..3
ok 1 - ("Aerosmith", "Queen", "The Strokes", "Sunny Day Real Estate")
ok 2 - ("The Animals", "The Cure", "Enrique Iglesias", "The Pixies", "The Ramones", "The Roots")
ok 3 - ("The The", "Thermodynamics", "The They")
```
[Answer]
## PowerShell v2+, ~~33~~ ~~32~~ 29 bytes
```
$args|sort{$_-replace'^the '}
```
*Saved 3 bytes thanks to @MathiasRJessen*
Input is via command-line arguments. Sorts the original names based on the results of the script block `{...}` that performs a regex `-replace` to strip out the leading (case-insensitive) `"the "`.
### Examples
```
PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'the Ramones' 'The cure' 'The Pixies' 'The Roots' 'the Animals' 'Enrique Iglesias'
the Animals
The cure
Enrique Iglesias
The Pixies
the Ramones
The Roots
PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'The The' 'The They' 'Thermodynamics'
The The
Thermodynamics
The They
PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'THE STOOGES' 'The Strokes' 'The The' 'the they' 'the band' 'STP'
the band
THE STOOGES
STP
The Strokes
The The
the they
```
[Answer]
# JavaScript/ECMAScript 6 ~~93~~ 70 bytes
**70** *Thanks to Neil and Downgoat for advice*
```
B=>B.sort((a,b)=>R(a).localeCompare(R(b)),R=s=>s.replace(/^the /i,''))
```
*Readable Version for the 70-byte variant*
```
let sortBandNames = (bandNames) => {
    let stripThe = (name) => name.replace(/^the /i, '');
    let compareFunc = (a, b) => stripThe(a).localeCompare(stripThe(b));
    return bandNames.sort(compareFunc)
};
```
**93**
```
f=B=>{R=s=>s.toLowerCase().replace(/the /,'');return B.sort((a,b)=>R(a).localeCompare(R(b)))}
```
*Readable Version for the 93-byte variant*
```
let sortBandNames = (bandNames) => {
    let stripThe = (name) => name.toLowerCase().replace(/the /, '');
    let compareFunc = (a, b) => stripThe(a).localeCompare(stripThe(b));
    return bandNames.sort(compareFunc)
};
```
[Answer]
## Java 8, 178 bytes
```
void q(String[]s){java.util.Arrays.sort(s,(a,b)->(a.toLowerCase().startsWith("the ")?a.substring(4):a).compareToIgnoreCase(b.toLowerCase().startsWith("the ")?b.substring(4):b));}
```
Ungolfed version:
```
void sort(String[] bands) {
    java.util.Arrays.sort(bands, (a, b) -> 
        (a.toLowerCase().startsWith("the ") ? a.substring(4) : a).compareToIgnoreCase(
            b.toLowerCase().startsWith("the ") ? b.substring(4) : b
        )
    );
}
```
Call as such:
```
public static void main(String[] args) {
    String[] bands = {"The Strokes", "Queen", "AC/DC", "The Band", "Cage the Elephant", "cage the elephant"};
    sort(bands); // or q(bands) in the golfed version
    System.out.println(java.util.Arrays.toString(bands));
}
```
[Answer]
## Bash + coreutils, 44 bytes
```
sed '/^the /I!s,^,@ ,'|sort -dk2|sed s,@\ ,,
```
**Explanation:** the input and output format is one band per line
```
sed '/^the /I!s,^,@ ,'   # prepend '@ ' to each line not starting with 'the ', case
                         #insensitive. This adds a temporary field needed by sort.
sort -dk2                # sort in ascending dictionary order by 2nd field onward
sed s,@\ ,,              # remove the temporary field
```
**Test run (using a here-document with EOF as the end marker):**
```
./sort_bands.sh << EOF
> Queen
> Aerosmith
> Sunny Day Real Estate
> The Strokes
> EOF
```
**Output:**
```
Aerosmith
Queen
The Strokes
Sunny Day Real Estate
```
[Answer]
# Vim, 18 bytes
Well now that I realized this is possible, I'm kinda embarrassed by my 26 byte V answer, especially since V is supposed to be shorter than vim. But this is pretty much a builtin.
```
:sor i/\(The \)*/<CR>
```
Explanation (straight from vim help):
```
                            *:sor* *:sort*
:[range]sor[t][!] [b][f][i][n][o][r][u][x] [/{pattern}/]
            Sort lines in [range].  When no range is given all
            lines are sorted.
            With [i] case is ignored.
            When /{pattern}/ is specified and there is no [r] flag
            the text matched with {pattern} is skipped, so that
            you sort on what comes after the match.
            Instead of the slash any non-letter can be used.
```
[Answer]
# C, ~~216~~ ~~212~~ 135 + 5 (`qsort`) = ~~221~~ ~~217~~ 140 bytes
```
M(void*a,void*b){char*A,*B;A=*(char**)a;B=*(char**)b;A=strcasestr(A,"The ")?A+4:A;B=strcasestr(B,"The ")?B+4:B;return strcasecmp(A,B);}
```
Well, I finally got around to finishing this in `C`. Golfing tips are very much appreciated.
In this submission, `M` is the comparison function to be supplied to [`qsort`](https://www.gnu.org/software/libc/manual/html_node/Array-Sort-Function.html#Array-Sort-Function). Therefore, to invoke this, you must use `qsort` in the format `qsort(argv++,argc--,8,M)` where `argv` contains the command-line arguments and `argc` is the number of arguments provided. 
[Try It Online!](https://tio.run/##TU89T8MwEJ2bX2EFIcWJgxiYcAuyBWMHKBswuI6TODR2sZ1IpcrPZjZ2iqDT3fu4d3e8bDj3F1Lx3VAJsLSukvqqvUvOKSNVEzi/zkYtq5yhuWzhkbfM5ATlFJNVns0ohwzTf7ANSgjgzIpQMoLSl1aAFN6T4uaWBOeZSP9EGkSKjXCDUeDXwft9GKcQT14qB3omVRYbZhqOTttiP0JwTBafVhuXRVgUKDrKEln5JXR9OgyiNcTJotZmzuhW17hbRh/uimJOWOzD167O0kv7ptKYMb5273FoSibvnwYhlCfCaNtL1/rNoNQBPLADeBZsBx6tY074@M7GGf0h7LfSJWe8FT8)
[Answer]
# [Nim](http://nim-lang.org/), 96 bytes
```
import algorithm,strutils,future
x=>x.sortedByIt toLower it[4*int(it.toLower[0..3]=="the ")..^0]
```
Those `import`s take up so many bytes `:|`
A translation of my [Python answer](https://codegolf.stackexchange.com/a/87456/56755).
This is an anonymous procedure; to use it, it must be passed into a testing procedure. Here's a full program you can use for testing:
```
import algorithm,strutils,future
proc test(x: seq[string] -> seq[string]) =
 echo x(@["The The", "The They", "Thermodynamics"]) # Substitute your input here
test(x=>x.sortedByIt toLower it[4*int(it.toLower[0..3]=="the ")..^0])
```
[Answer]
# Haskell, 84 bytes
```
import Data.List
p(t:'h':'e':' ':s)|elem t"Tt"=s
p s=s
sortBy(\a b->p a`compare`p b)
```
Call with
```
sortBy(\a b->p a`compare`p b)["The The", "The They", "Thermodynamics"]
```
Testcase:
```
let s = sortBy(\a b->p a`compare`p b)
and[s["Queen", "Aerosmith", "Sunny Day Real Estate", "The Strokes"]==["Aerosmith", "Queen", "The Strokes", "Sunny Day Real Estate"],s["The Ramones", "The Cure", "The Pixies", "The Roots", "The Animals", "Enrique Iglesias"]==["The Animals", "The Cure", "Enrique Iglesias", "The Pixies", "The Ramones", "The Roots"],s["The The", "The They", "Thermodynamics"]==["The The", "Thermodynamics", "The They"]]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
```
tk'^the '[]YX2$S
```
Input format is (each line corresponds to a test case)
```
{'Queen', 'Aerosmith', 'Sunny Day Real Estate', 'The Strokes'} 
{'The Ramones', 'The Cure', 'The Pixies', 'The Roots', 'The Animals', 'Enrique Iglesias'}
{'The The', 'The They', 'Thermodynamics'}
```
[**Try it online!**](http://matl.tryitonline.net/#code=dGsnXnRoZSAnW11ZWDIkUw&input=eydRdWVlbicsICdBZXJvc21pdGgnLCAnU3VubnkgRGF5IFJlYWwgRXN0YXRlJywgJ1RoZSBTdHJva2VzJ30g)
### Explanation
```
t        % Implicitly input cell array of strings. Push another copy
k        % Convert to lowercase
'^the '  % String to be used as regex pattern: matches initial 'the '
[]       % Empty array
YX       % Regex replacement: replace initial 'the ' in each string by empty array
2$S      % Sort input according to the modified cell array. Implicitly display
```
[Answer]
# C#, 139 Bytes
```
using System.Linq;System.Collections.IEnumerable S(string[] l)=> l.OrderBy(b=>(b.ToLower().StartsWith("the ")?b.Substring(4):b).ToLower());
```
[Try online!](http://csharppad.com/gist/7f2a6e59f3525c4e81fe1068956400a4)
Without counting the usings the answer would be 102 bytes.
[Answer]
**BASH, 64 Bytes**
```
sed 's/^the / /;s/^The /    /'|sort -fb|sed 's/^ /the /;s/^ /The /'
```
Input: stdin, one band per line.
Output: stdout
Note: The second replacements (s/^The/ / and s/^ /The /) use the tab character, so they don't always copy/paste correctly.
[Answer]
# Groovy, 34 bytes
```
{it.sort{it.toLowerCase()-'the '}}
```
41% my answer is `.toLowerCase()`, kill me now.
---
# Output
When running...
```
({it.sort{it.toLowerCase()-'the '}})(['The ramones','The Cure','The Pixies','The Roots','The Animals','Enrique Iglesias'])
```
The result is...
`[The Animals, The Cure, Enrique Iglesias, The Pixies, The ramones, The Roots]`
With no debug or error output.
[Answer]
# q/kdb+, ~~36~~ 33 bytes
**Solution:**
```
{x(<)@[x;(&)x like"[Tt]he *";4_]}
```
**Example:**
```
q){x(<)@[x;(&)x like"[Tt]he *";4_]}("Queen";"Aerosmith";"Sunny Day Real Estate";"The Strokes";"the Eagles")
"Aerosmith"
"the Eagles"
"Queen"
"The Strokes"
"Sunny Day Real Estate"
```
**Explanation:**
Strip out any "[Tt]he " from each input string, sort this list, then sort the original list based on the indexing of the sorted list.
```
{x iasc @[x;where x like "[Tt]he *";4_]} / ungolfed solution
{                                      } / lambda function
        @[x;                       ;  ]  / apply function to x at indices
                                    4_   / 4 drop, remove first 4 items
            where x like "[Tt]he *"      / where the input matches 'The ...' or 'the ...'
   iasc                                  / returns sorted indices
 x                                       / index into original list at these indices
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~11~~ 10 bytes
```
ñ_v r`^e 
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=8V92IHJgXpBlIA==&input=WyJUaGUgUmFtb25lcyIsIlRoZSBDdXJlIiwiVGhlIFBpeGllcyIsIlRoZSBSb290cyIsIlRoZSBBbmltYWxzIiwiRW5yaXF1ZSBJZ2xlc2lhcyIsIlF1ZWVuIiwiQWVyb3NtaXRoIiwiU3VubnkgRGF5IFJlYWwgRXN0YXRlIiwiVGhlIFN0cm9rZXMiLCJUaGUgVGhlIiwiVGhlIFRoZXkiLCJUaGVybW9keW5hbWljcyIsInRoZSBwQXBlciBjaEFzZV0=)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 27 bytes
```
vyð¡RD¤…TheQsgα£Rðý})‚øí{ø¤
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/rPLwhkMLg1wOLXnUsCwkIzWwOP3cxkOLgw5vOLy3VvNRw6zDOw6vrT6849CS//@jlYAKFIBYSUcBxqyEsoty81Mq8xJzM5OLlWIB "05AB1E – Try It Online")
### Explanation
```
vyð¡RD¤…TheQsgα£Rðý})‚øí{ø¤   Argument l
v                 }           For each y in l, do:
 yð¡                            Split y on space
    RD                          Reverse and duplicate
      ¤…TheQ                    Last element equals "The" (true = 1, false = 0)
            sgα                 Absolute difference with length of array
               £                Get elements from index 0 to calculated difference
                R               Reverse
                 ðý             Join on space
                    )‚øí      Pair each element with original
                        {ø¤   Sort and get the original band name
```
[Answer]
# Java ~~176~~ 158 bytes
```
public String[]sort(String[]names){
  for(int i=-1;++i<names.length;)
    if(names[i].startsWith("(The |the )"))
      names[i]=names[i].substring(4);
  return Arrays.sort(names,String.CASE_INSENSITIVE_ORDER);
  }
```
Main Function
```
public static void main(String[]args){
  Scanner s = new Scanner(System.in);
  List<String> list= new ArrayList<>();
  while(!(String h = s.nextLine).equalsIgnoreCase("~")){
    list.add(h);
  }
System.out.println(sort(list.toArray(newString[0]))
```
);
 }
Golfed sort function:
```
String[]s(String[]n){for(int i=-1;++i<n.length;)if(n[i].startsWith("(The |the )"))n[i]=n[i].substring(4);return Arrays.sort(n,String.CASE_INSENSITIVE_ORDER);}
```
> 
> Thanks to @raznagul for saving 18 bytes
> 
> 
> 
]