I got a problem when I tried to sort the title alphabetically in my small project. There is a variable "sortedRows", which stores the sorted rows after using "sort" function. The webpage is listed below.
function sortTitle(){
const rows = Array.from(document.querySelectorAll(".tbody")); # get the table rows
const sortedRows = rows.sort((a, b) => {
const aText = a.querySelectorAll("td")[1];
const bText = b.querySelectorAll("td")[1];
if(aText.textContent > bText.textContent){
return -1;
}
if(aText.textContent.toLowerCase() < bText.textContent.toLowerCase()){
return 1;
}
return 0;
})
const newRows = document.getElementsByClassName("tbody");
for (let i = 0; i < rows.length; i++){
console.log(sortedRows[i].innerHTML); # I tried to replace the rows with sortedrows, but here is an error. The test1 and dwc did not swap
newRows[i].innerHTML = sortedRows[i].innerHTML;
}
};
Before the for loop in the code chuck, I found the sortedRows[0] is dwc and sortedRows1 is test1, however, in after the for loop, both sortedRows[0] and sortedRows1 are dwc. I am not sure what happened when I tried to "newRows[i].innerHTML = sortedRows[i].innerHTML;". I will be appreciated if anyone can help me find the problem.
I don't have the ability to test your code, but I can suggest that instead of trying to replace the elements of newRows inside of the for loop you can use something like this:
newRows = [...sortedRows];
In JS this is called spread operator. Using it like this with one dimension array is beneficial to make a shallow copy. In a nutshell, using this you can clone the entire content of sortedRows into new Rows. You may find this article of FreeCodeCamp interesting:.