user3413623
user3413623

Reputation: 80

Jquery reverse sorting

I have this code:

 $(document).ready(function() {
        ofertas_sort = function(sort_key) {
            // array of offer divs
            var ofertas = $('.infoferta');

            // the div classname corresponding to the key by which
            // we are sorting
            var sort_key_sel = 'div.' + sort_key;

            // in large lists it'd be more efficient to calculate
            // this data pre-sort, but for this instance it's fine
            ofertas.sort(function(a, b) {
                return parseInt($(sort_key_sel, a).attr('data-value')) -
                    parseInt($(sort_key_sel, b).attr('data-value'));
            });

            // re-fill the container with the newly-sorted divs
            $('#ofertas_container').empty().append(ofertas);
        };

        $('a').click(function() {
            ofertas_sort($(this).attr('data-key'));
        });
    });

I need to do the reverse.. but when i put lines like this:

 ofertas.reverse(function(i, e) {
            alert(i);
            alert(e);
        });

it shows this message

Uncaught TypeError: Object [object Object] has no method 'reverse'

Upvotes: 1

Views: 4057

Answers (2)

user166390
user166390

Reputation:

ofertas is not an array -- it is a jQuery object -- and is missing such a method called reverse (see jQuery API). Likewise, I am surprised the posted example code works because sort is being invoked upon ofertas.

To "reverse sort" just multiply the result of the comparator (sort function) by -1 or invert the operands of the subtraction operation (which is effectively the same thing here).

Happy coding.

Upvotes: 1

Mike Lewis
Mike Lewis

Reputation: 64177

ofertas is a jQuery object, however you can convert it to an array by using the toArray() method. From there you can call array functions such as reverse.

Upvotes: 1

Related Questions