1

How to sort rows using jquery. My aim is to just find the item with min price. Not actually sort the table.

This below code always shows the first row which is not actually right.

        var rows =  $('tr');
        rows.sort(function(a, b){
            var p1 = parseInt(a.querySelector('td.item') ? a.querySelector('td.item').innerText : 0)
            var p2 = parseInt(b.querySelector('td.item') ? b.querySelector('td.item').innerText : 0);
            return p1 > p2;
        });
        console.log(rows[0])

1 Answer 1

2

Your sort function should return p1 - p2, you need minus for less than, 0 for equal and positive for greater than not a boolean with p1 > p2.

You could just create a compare function with an Intl.Collator.

const naturalSort = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare;

rows.sort((a, b) => naturalSort(
  a.querySelector('td.item') && a.querySelector('td.item').innerText,
  b.querySelector('td.item') && b.querySelector('td.item').innerText
));

console.log(rows[0]);

It will take care of the numeric comparisons for you.

Sign up to request clarification or add additional context in comments.

Comments

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.