|
| 1 | +# Exercise 17: Sort Without Articles |
| 2 | +Nitish Dayal, Software & Applications Developer - [Contact](http://nitishdayal.me) |
| 3 | +Last Commit Date: Dec 23, 2016 |
| 4 | + |
| 5 | +We're given an HTML page with an _unordered list_, and an _array of string |
| 6 | + values_ in the `script` tag. Sort the values in the array **excluding |
| 7 | + the prefixes 'The', A', or 'An'** and place the values into the _unordered |
| 8 | + list_ as _list items_. |
| 9 | + |
| 10 | +## Guide |
| 11 | + |
| 12 | +Declare a `const` variable and define it as a _regular expression pattern_ |
| 13 | + that will match the prefixes we want to exclude that is **case insensitive**. |
| 14 | + Create a function that will accept a string value as a parameter and |
| 15 | + and returns the string after replacing any parts of the string that match |
| 16 | + the previously defined _regular expression pattern_ with an empty string, |
| 17 | + excluding leading or trailing whitespaces. Declare a `const` and define |
| 18 | + it as the result of sorting through the provided array, passing each |
| 19 | + item in the array to the previously defined function. FInally, target |
| 20 | + the _unordered list_ and update its _inner HTML_ to display each item |
| 21 | + in the array as a _list item_. |
| 22 | + |
| 23 | +**Steps:** |
| 24 | + |
| 25 | +1. Declare a `const` variable and define as a new Regular Expression object. |
| 26 | + |
| 27 | + ```JavaScript |
| 28 | + const namesPrefix = new RegExp('^(a |the |an )', 'i') |
| 29 | + ``` |
| 30 | + |
| 31 | +2. Declare a `const` and define it as an _arrow function_ which accepts |
| 32 | + a parameter `bandName` and returns the provided argument after replacing |
| 33 | + any values that match the previously defined RegEx pattern with an empty |
| 34 | + string and removing any leading or trailing whitespace. |
| 35 | + |
| 36 | + ```JavaScript |
| 37 | + const stripPrefixes = (bandName) => bandName.replace(namesPrefixes, '').trim() |
| 38 | + ``` |
| 39 | + |
| 40 | +3. Declare a `const` and define it as the **result** of sorting through the `bands` |
| 41 | + array, passing each item into the `stripPrefixes` function to remove prefixes (if |
| 42 | + they exist) before comparing them. |
| 43 | + |
| 44 | + ```JavaScript |
| 45 | + const sortedBands = bands.sort((a, b) => stripPrefixes(a) > stripPrefixes(b) ? 1 : -1) |
| 46 | + ``` |
| 47 | + |
| 48 | +4. Select the `#bands` unordered list and update the _inner HTML_ to be the items in |
| 49 | + the sortedBands array stored within _list items_. |
| 50 | + |
| 51 | + ```JavaScript |
| 52 | + document.querySelector('#bands).innerHTML = |
| 53 | + sortedBands |
| 54 | + .map(band => `${<li>${band}</li>`}) |
| 55 | + .join('') |
| 56 | + ``` |
| 57 | + |
| 58 | +Another one down, another one down, another one bites the dust! HEY! |
0 commit comments