1 min read views
Day17: Sort Without Articles
How to sort arrays in JavaScript while ignoring articles.
Introduction: How to sort arrays in JavaScript while ignoring articles.
Project Page: https://iris1114.github.io/javascript30/17_Sort-Without-Articles/
HTML
- Contains a
ullist for displaying sorted band names.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Sort Without Articles</title>
</head>
<body>
<ul id="bands"></ul>
</body>
</html>CSS
- Sets up basic page styling including fonts, colors, and layout
- Styles for the bands list and list items
html {
font-family: sans-serif;
background: #ffc600;
color: #333;
font-size: 20px;
}
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
#bands {
list-style: inside square;
font-size: 20px;
background: white;
width: 500px;
margin: auto;
padding: 0;
box-shadow: 0 0 0 20px rgba(0, 0, 0, 0.05);
}
#bands li {
border-bottom: 1px solid #efefef;
padding: 20px;
}
#bands li:last-child {
border-bottom: 0;
}
a {
color: #ffc600;
text-decoration: none;
}JavaScript
- Sorts band names while ignoring articles (The, A, An)
- Renders sorted band names to the
ullist
const bands = [
'The Plot in You',
'The Devil Wears Prada',
'Pierce the Veil',
'Norma Jean',
'The Bled',
'Say Anything',
'The Midway State',
'We Came as Romans',
'Counterparts',
'Oh, Sleeper',
'A Skylit Drive',
'Anywhere But Here',
'An Old Dog',
]
function strip(bandName) {
return bandName.replace(/^(a |the |an )/i, '').trim()
}
const sortedBands = bands.sort((a, b) => (strip(a) > strip(b) ? 1 : -1))
document.querySelector('#bands').innerHTML = sortedBands
.map((band) => `<li>${band}</li>`)
.join('')Note
- Uses regular expressions to remove articles from band names
- Uses
Array.prototype.sortto sort band names - Uses
Array.prototype.mapto generate HTML list items
Related Posts
1 min read
Day28: Video Speed Controller
How to implement video playback speed control using JavaScript.