jQuery函数从数组中获取所有唯一元素?

Cra*_*lot 72 javascript jquery jquery-selectors

jQuery.unique允许您获取数组的唯一元素,但文档称该函数主要供内部使用,并且仅对DOM元素进行操作.另一个SO响应表示该unique()函数对数字起作用,但是这个用例不一定是未来证据,因为它没有在文档中明确说明.

鉴于此,是否存在一个"标准"jQuery函数,用于仅访问数组中的唯一值 - 特别是整数等基元?(显然,我们可以使用函数构造一个循环each(),但我们是jQuery的新手,并且想知道是否有专用的jQuery函数.)

ken*_*bec 124

您可以array.filter用来返回每个不同值的第一项 -

var a = [ 1, 5, 1, 6, 4, 5, 2, 5, 4, 3, 1, 2, 6, 6, 3, 3, 2, 4 ];

var unique = a.filter(function(itm, i, a) {
    return i == a.indexOf(itm);
});

console.log(unique);
Run Code Online (Sandbox Code Playgroud)

如果支持IE8及以下版本是主要的,请不要使用不受支持的filter方法.

除此以外,

if (!Array.prototype.filter) {
    Array.prototype.filter = function(fun, scope) {
        var T = this, A = [], i = 0, itm, L = T.length;
        if (typeof fun == 'function') {
            while(i < L) {
                if (i in T) {
                    itm = T[i];
                    if (fun.call(scope, itm, i, T)) A[A.length] = itm;
                }
                ++i;
            }
        }
        return A;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 警告:以上代码在IE8及更低版本中是BREAKS,它们对"Array.filter"或"Array.indexOf"没有本机支持.有关在jquery支持的浏览器中没有中断的代码,请参阅我对此答案的修订版. (4认同)
  • @cwolves' 的答案应该是公认的。这个答案以及几乎所有其他答案都在 O(n^2) 时间内运行,如果您在大数组上尝试它,将会**非常非常**慢。 (2认同)

js1*_*568 48

只需使用此代码作为简单JQuery插件的基础.

$.extend({
    distinct : function(anArray) {
       var result = [];
       $.each(anArray, function(i,v){
           if ($.inArray(v, result) == -1) result.push(v);
       });
       return result;
    }
});
Run Code Online (Sandbox Code Playgroud)

用法如下:

$.distinct([0,1,2,2,3]);
Run Code Online (Sandbox Code Playgroud)


Den*_*nis 13

基于@ kennebec的答案,但修复了IE8及以下版本,通过在数组周围使用jQuery包装器来提供缺少的Array函数filterindexOf:

$ .makeArray()包装器可能不是绝对需要的,但是如果你省略这个包装器你会得到奇怪的结果,否则你会得到JSON.stringify结果.

var a = [1,5,1,6,4,5,2,5,4,3,1,2,6,6,3,3,2,4];

// note: jQuery's filter params are opposite of javascript's native implementation :(
var unique = $.makeArray($(a).filter(function(i,itm){ 
    // note: 'index', not 'indexOf'
    return i == $(a).index(itm);
}));

// unique: [1, 5, 6, 4, 2, 3]
Run Code Online (Sandbox Code Playgroud)


law*_*sea 9

我会使用underscore.js,它提供了一个uniq你想要的方法.


Rub*_*der 7

    // for numbers
    a = [1,3,2,4,5,6,7,8, 1,1,4,5,6]
    $.unique(a)
    [7, 6, 1, 8, 3, 2, 5, 4]

    // for string
    a = ["a", "a", "b"]
    $.unique(a)
    ["b", "a"]
Run Code Online (Sandbox Code Playgroud)

对于dom元素,我想这里没有例子,因为你已经知道了!

这是现场示例的jsfiddle链接:http: //jsfiddle.net/3BtMc/4/

  • 但文档说只有$ .unique()**才能在DOM元素上运行!"对一组DOM元素进行排序,删除重复项.请注意,这仅适用于DOM元素的数组,而不是字符串或数字." - http://api.jquery.com/jquery.unique/ (7认同)

Mar*_*ahn 6

当你遇到它们时,走遍数组并将项目推送到哈希.交叉引用每个新元素的哈希值.

请注意,这仅适用于基元(字符串,数字,null,未定义,NaN)和一些序列化为相同内容的对象(函数,字符串,日期,可能是数组,具体取决于内容).这里的哈希会碰撞,因为它们都序列化为相同的东西,例如"[object Object]"

Array.prototype.distinct = function(){
   var map = {}, out = [];

   for(var i=0, l=this.length; i<l; i++){
      if(map[this[i]]){ continue; }

      out.push(this[i]);
      map[this[i]] = 1;
   }

   return out;
}
Run Code Online (Sandbox Code Playgroud)

也没有理由不能使用jQuery.unique.我唯一不喜欢的是它破坏了数组的顺序.如果您有兴趣,这是它的确切代码:

Sizzle.uniqueSort = function(results){
    if ( sortOrder ) {
        hasDuplicate = baseHasDuplicate;
        results.sort(sortOrder);

        if ( hasDuplicate ) {
            for ( var i = 1; i < results.length; i++ ) {
                if ( results[i] === results[i-1] ) {
                    results.splice(i--, 1);
                }
            }
        }
    }

    return results;
};
Run Code Online (Sandbox Code Playgroud)


Mot*_*tie 5

Paul Irish有一个" Duck Punching "方法(参见示例2),它修改jQuery的$.unique()方法以返回任何类型的唯一元素:

(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);
Run Code Online (Sandbox Code Playgroud)


小智 5

这是js1568的解决方案,经过修改后可以处理通用的对象数组,例如:

 var genericObject=[
        {genProp:'this is a string',randomInt:10,isBoolean:false},
        {genProp:'this is another string',randomInt:20,isBoolean:false},
        {genProp:'this is a string',randomInt:10,isBoolean:true},
        {genProp:'this is another string',randomInt:30,isBoolean:false},
        {genProp:'this is a string',randomInt:40,isBoolean:true},
        {genProp:'i like strings',randomInt:60,isBoolean:true},
        {genProp:'this is a string',randomInt:70,isBoolean:true},
        {genProp:'this string is unique',randomInt:50,isBoolean:true},
        {genProp:'this is a string',randomInt:50,isBoolean:false},
        {genProp:'i like strings',randomInt:70,isBoolean:false}
    ]
Run Code Online (Sandbox Code Playgroud)

它接受一个名为propertyName的参数,猜!:)

  $.extend({
        distinctObj:function(obj,propertyName) {
            var result = [];
            $.each(obj,function(i,v){
                var prop=eval("v."+propertyName);
                if ($.inArray(prop, result) == -1) result.push(prop);
            });
            return result;
        }
    });
Run Code Online (Sandbox Code Playgroud)

因此,如果您需要提取给定属性的唯一值列表,例如用于randomInt属性的值,请使用以下命令:

$.distinctObj(genericObject,'genProp');
Run Code Online (Sandbox Code Playgroud)

它返回一个这样的数组:

["this is a string", "this is another string", "i like strings", "this string is unique"] 
Run Code Online (Sandbox Code Playgroud)


jag*_*oft 5

function array_unique(array) {
    var unique = [];
    for ( var i = 0 ; i < array.length ; ++i ) {
        if ( unique.indexOf(array[i]) == -1 )
            unique.push(array[i]);
    }
    return unique;
}
Run Code Online (Sandbox Code Playgroud)