Sachin Nagpal
Sachin Nagpal

Reputation: 23

Jquery sort function not working on Chrome Browser

I am shorting div based on data attribute values. My existing code running fine on Firefox, but it not working on Chrome Browser.

Here's my code:

$('select#shorting-job').change(function(e) {
            var $list = $('.adsence-right');
            var $productList = $('div.show-jobs-in-right',$list);
            $productList.sort(function(a, b){
                var keyA = $(a).attr("data-salary");
                var keyB = $(b).attr("data-salary");
                if($('#shorting-job').val()=='Salary'){
                  return false; 
                }else if($('#shorting-job').val()=='asc'){
                    return (parseInt(keyA) > parseInt(keyB)) ? 1 : 0;
                } else {
                    return (parseInt(keyA) < parseInt(keyB)) ? 1 : 0;
                }
            });
            $.each($productList, function(index, row){
                $list.append(row);
            });
            e.preventDefault();
    });

Upvotes: 1

Views: 1590

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386578

You need to return a symetrical result for ascending and descending sorting which uses the negative values as well.

You could use the value you have and return the delta of it.

return keyA - keyB;

For descending order, you might reverse the order of subtraction

return keyB - keyA;

In both cases the values are converted to number because of using the minus sign and the implicid casting to number.

The main reason to get a different result in different browsers is, that if the order is not really different, you might get an unstable result, as Array#sort is not stable.

Upvotes: 2

Related Questions