jQuery.unique on an array of strings

后端 未结 8 561
野趣味
野趣味 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:29

    Although it works, you should probably take into consideration the function description. If the creators say that it is not designed for filtering arrays of anything else than dom elements, you should probably listen to them.
    Besides, this functionality is quite easy to be reproduced :

    function unique(array){
        return array.filter(function(el, index, arr) {
            return index === arr.indexOf(el);
        });
    }
    

    (demo page)

    Update:

    In order for this code to work in all browsers (including ie7 that doesn't support some array features - such as indexOf or filter), here's a rewrite using jquery functionalities :

    • use $.grep instead of Array.filter
    • use $.inArray instead of Array.indexOf

    Now here's how the translated code should look like:

    function unique(array) {
        return $.grep(array, function(el, index) {
            return index === $.inArray(el, array);
        });
    }
    

    (demo page)

提交回复
热议问题