https://github.com/gerhynes/sort-without-articles
A page built to practice sorting arrays. Built for Wes Bos' JavaScript 30 course.
https://github.com/gerhynes/sort-without-articles
javascript javascript30 sort
Last synced: 10 months ago
JSON representation
A page built to practice sorting arrays. Built for Wes Bos' JavaScript 30 course.
- Host: GitHub
- URL: https://github.com/gerhynes/sort-without-articles
- Owner: gerhynes
- Created: 2017-10-18T21:04:18.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2018-01-22T22:07:09.000Z (about 8 years ago)
- Last Synced: 2025-01-31T11:34:28.247Z (about 1 year ago)
- Topics: javascript, javascript30, sort
- Language: JavaScript
- Homepage: https://gk-hynes.github.io/sort-without-articles/
- Size: 1.95 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Sort Without Articles
A page built to practice sorting arrays. Built for Wes Bos' [JavaScript 30](https://javascript30.com/) course.
[](https://gk-hynes.github.io/sort-without-articles/)
## Notes
To sort the bandnames, create a variable, `sortedBands`, and call `sort` on it.
`Sort` takes a function with parameters, `a` and `b`, the first and second element passed to it. It moves the bigger one, or the one that comes first alphabetically, to the top.
Inside `sort`, use an if statment to check if `a > b`.
This will alphabetize the array but will take articles into account.
So, make a new function, `strip`, and pass it `bandName`.
Return `bandName` but run `replace` on it. You can use a regular expression to replace a, an, and the in one go. Call `trim` on the end of it to remove unnecessary spaces.
```js
function strip(bandName) {
return bandName.replace(/^(a |the |an )/i, "").trim();
}
```
Back inside the `sort` function, you can use a ternary operator, calling `strip` on `a` and `b`.
```js
const sortedBands = bands.sort((a, b) => (strip(a) > strip(b) ? 1 : -1));
```
### Displaying the bands
Now you can select the ul `bands` and set their innerHTML.
Take `sortedBands`, loop over them using `map`, return each band inside an li, and `join` them.
```js
document.querySelector("#bands").innerHTML = sortedBands
.map(band => `
.join("");
```
When you try to set something to innerHTML that is not a string, such as an array, `toString` is called on it and by default a comma is put between each element.
`join("")` prevents this and joins the elements into one big string.