I have created this basic use case of .sort()
for my own reference. I am asking for a review to see if there are bad practices present or areas that could be optimised.
- Is my use of modifying the array correct? Do I need to place the newly sorted list into a new array?
- Using
.map()
I found it was parsing it as a string. IsinsertAdjacentHTML()
the right method to use here?
const listArea = document.getElementById('listArea');
const btnAsc = document.getElementById('asc');
const btnDes = document.getElementById('des');
// The Original Array
let architects = [
"Lloyd Wright",
"Hadid",
"Mies van der Rohe",
"Le Corbusier",
"Foster",
"Gaudi",
"Piano",
"Gropius",
"Niemeyer",
"Aalto",
"Saarinen",
]
// Empty Array to Store Sorted Array
let sortedList = [];
// Click Events for the sort buttons
btnAsc.addEventListener('click', () => sortAsc(architects));
btnDes.addEventListener('click', () => sortDes(architects));
// Sort the array in ascending order
function sortAsc(arr) {
// Clear the sortedList array
sortedList.length = 0;
// Convert each item in the architects array to lower case
for(const element of arr) {
// Push these lowercase elements into the sortedList array
sortedList.push(element.toLowerCase());
}
sortedList.sort();
populateList(sortedList);
}
function sortDes(arr) {
sortedList.length = 0;
for(const element of arr) {
sortedList.push(element.toLowerCase());
}
sortedList.sort().reverse();
populateList(sortedList);
}
function populateList(arr) {
// Empty out the listArea of all content
while(listArea.firstChild) {
listArea.removeChild(listArea.lastChild);
}
// Map each item in the supplied array to an li, and remove comma at end of each
let listArchitects = arr.map(item => `<li>${item}</li>`).join('');
listArea.insertAdjacentHTML('beforeend', listArchitects);
}
window.addEventListener('onload', populateList(architects));
#listArea {
text-transform: capitalize;
}
<div class="list">
<div class="buttons">
<button id="asc">Sort Ascending</button>
<button id="des">Sort Descending</button>
</div>
<ul id="listArea">
</ul>
</div>