0

I have problem with sort column "wins" in javascript. I don't know why 19 is in the middle, it should be last or first. Every number from 1 to 9 are sorted correct. Below are screen after sort and my code.

enter image description here enter image description here

/**
 * Sorts a HTML table.
 *
 * @param {HTMLTableElement} table The table to sort
 * @param {number} column The index of the column to sort
 * @param {boolean} asc Determines if the sorting will be in ascending
 */
function sortTableByColumn(table, column, asc = true) {
    const dirModifier = asc ? 1 : -1
    const tBody = table.tBodies[0]
    const rows = Array.from(tBody.querySelectorAll('tr'))

    // Sort each row
    const sortedRows = rows.sort((a, b) => {
        const aColText = a.querySelector(`td:nth-child(${column + 1})`).textContent.trim()
        const bColText = b.querySelector(`td:nth-child(${column + 1})`).textContent.trim()

        console.log(aColText)
        console.log(bColText)

        return aColText > bColText ? 1 * dirModifier : -1 * dirModifier
    })

    // Remove all existing TRs from the table
    while (tBody.firstChild) {
        tBody.removeChild(tBody.firstChild)
    }

    // Re-add the newly sorted rows
    tBody.append(...sortedRows)

    // Remember how the column is currently sorted
    table.querySelectorAll('th').forEach(th => th.classList.remove('th-sort-asc', 'th-sort-desc'))
    table.querySelector(`th:nth-child(${column + 1})`).classList.toggle('th-sort-asc', asc)
    table.querySelector(`th:nth-child(${column + 1})`).classList.toggle('th-sort-desc', !asc)
}

export function activeSort() {
    document.querySelectorAll('.toSort').forEach(headerCell => {
        headerCell.addEventListener('click', () => {
            const tableElement = headerCell.parentElement.parentElement.parentElement
            const headerIndex = Array.prototype.indexOf.call(headerCell.parentElement.children, headerCell)
            const currentIsAscending = headerCell.classList.contains('th-sort-asc')

            sortTableByColumn(tableElement, headerIndex, !currentIsAscending)
        })
    })
}
DaroGawlik
  • 37
  • 5

1 Answers1

0

Your sorting stringss which are sorted lexicographically. If you want to sort by numbers parse your string to a number first e.g. using Number() or Number.parseInt().

const numberStrings = ["2", "19", "1"]
const numbers = [2, 19, 1];

const sortArray = (array) => {
  array.sort((a, b) => a > b ? 1: -1); // here you're working with strings
  return array;
};

console.log(sortArray(numberStrings));
console.log(sortArray(numbers));

By the way: one of the interesting bits of working with JavaScript will make the following work.

const numberStrings = ["2", "19", "1"]
const numbers = [2, 19, 1];

const sortArray = (array) => {
  array.sort((a, b) => a - b); // here JS will convert your strings to numbers and do the calculation
  return array;
};

console.log(sortArray(numberStrings));
console.log(sortArray(numbers));

JavaScript will automatically do the conversion for you when using - as this is the only way the - operator can be interpreted in that case.

<, > or === however have different semantic meaning (lexicographic ordering vs. natural order of numbers) for numbers and strings, therefore your solution won't work.

const resultStrings = "1" - "2";
console.log(resultStrings);
const resultNumbers = 1 - 2;
console.log(resultNumbers);

When we exchange the - with a plus however, this won't work, as + for strings means concatenation.

const resultStrings = "1" + "2";
console.log(resultStrings);
const resultNumbers = 1 + 2;
console.log(resultNumbers);
Mushroomator
  • 6,516
  • 1
  • 10
  • 27