1

I have sorted my html table, and I wanted to do a subsort. cant seems to figure out what's wrong with my code, been stuck here for a while now. I am trying to sort table on columns 4 then if there is any value identical sort them by id

let table = document.querySelector('tbody')
function sort() {

  let tr = table.children;
  let test1 = [...tr]
    .sort((a, b) => parseInt(b.children[3].innerHTML) - parseInt(a.children[3].innerHTML))
    .map(el => table.append(el));

  let test2 = [...tr]
    .sort((a, b) => {
        if (a.children[3].innerHTML === b.children[3].innerHTML)
          return parseInt(a.children[0].innerHTML) - parseInt(b.children[0].innerHTML)
      }
    })
.map(el => table.append(el));

};
==HTML==
<table class="table">
    <thead>
        <tr class='table_row'>
            <th>id</th>
            <th>header2</th>
            <th>header3</th>
            <th>header4</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>5</td>
            <td>data1</td>
            <td>jone</td>
            <td>170</td>
        </tr>
        <tr>
            <td>1</td>
            <td>data2</td>
            <td>josh</td>
            <td>170</td>
        </tr>
        <tr>
            <td>2</td>
            <td>data3</td>
            <td>adrian</td>
            <td>270</td>
        </tr>
        <tr>
            <td>8</td>
            <td>data4</td>
            <td>merry</td>
            <td>70</td>
        </tr>
    </tbody>
</table>
3
  • Please also post your HTML. Commented Apr 20, 2019 at 4:22
  • check your console as well Commented Apr 20, 2019 at 4:42
  • return a.children[3].innerHTML - b.children[3].innerHTML || parseInt(a.children[0].innerHTML) - parseInt(b.children[0].innerHTML) Commented Apr 20, 2019 at 4:57

1 Answer 1

1

You need to have both property checks in the same sort function. If you call a sort after another sort you will end up resorting your list and the original sort has no impact. And that makes sense if you think about it. Some pseudo code for what you’d want. There are more compact/elegant ways but this illustrates what you’d do. And if you understand doing two then you can do three etc etc.

function sort(a,b){
    const firstPropCompare = a.first - b.first;
    If(firstPropCompare != 0) return firstPropCompare;
    const secondCompare = a.second - b.second;
    return secondCompare;
}
Sign up to request clarification or add additional context in comments.

1 Comment

yes it works, do you mind sharing the more elegant/compact way? I wanted to learn

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.