jQuery.unique on an array of strings

后端 未结 8 581
野趣味
野趣味 2020-11-29 05:16

The description of jQuery.unique() states:

Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays

8条回答
  •  无人及你
    2020-11-29 05:35

    There's a quick way to extend the jQuery.unique() function to work on arrays containing elements of any type.

    (function($){
    
        var _old = $.unique;
    
        $.unique = function(arr){
    
            // do the default behavior only if we got an array of elements
            if (!!arr[0].nodeType){
                return _old.apply(this,arguments);
            } else {
                // reduce the array to contain no dupes via grep/inArray
                return $.grep(arr,function(v,k){
                    return $.inArray(v,arr) === k;
                });
            }
        };
    })(jQuery);
    
    // in use..
    var arr = ['first',7,true,2,7,true,'last','last'];
    $.unique(arr); // ["first", 7, true, 2, "last"]
    
    var arr = [1,2,3,4,5,4,3,2,1];
    $.unique(arr); // [1, 2, 3, 4, 5]
    

    http://www.paulirish.com/2010/duck-punching-with-jquery/ - example #2

提交回复
热议问题