How to 'pop' or 'shift' from jQuery set

In Javascript, arrays should have methods pop and shift.

However, JQuery objects seem to be missing these methods:

$('div').shift(); // Error, shift is undefined
$('div').pop(); // Error, pop is undefined
$('div').splice(); // Splice is OK actually

I wonder why these functions are missing - after all, the jquery object is just an array.

What's the easiest way of performing pop and shift functions on jquery objects?


Solution 1:

They're missing because a jQuery object isn't an Array.

(function( $ ) {
    $.fn.pop = function() {
        var top = this.get(-1);
        this.splice(this.length-1,1);
        return top;
    };

    $.fn.shift = function() {
        var bottom = this.get(0);
        this.splice(0,1);
        return bottom;
    };
})( jQuery );

EDIT: .slice() doesn't modify the original object. Fixed to use .splice() instead.

Solution 2:

Your safest bet would be to just use:

[].pop.call($('div'))
[].shift.call($('div'))

If you want to use the exact syntax in your example you can augment jQuery.fn:

jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;

The latter works well for the mutator methods. It'll work for the accessor and iteration methods too, but be advised that many of those returns a pure array that you'd have to rewrap. Be aware that jQuery has is own version of some of these (e.g. .map, .slice, .filter, etc.) that you probably don't want to overwrite.