关于字符串数组的jQuery.unique

时间:2021-02-27 13:39:50

The description of jQuery.unique() states:

jQuery.unique()的描述说明:

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

在适当的位置对DOM元素数组进行排序,并删除重复项。请注意,这仅适用于DOM元素的数组,而不适用于字符串或数字。

With the description in mind, can someone explain why the code below works?

考虑到描述,有人可以解释为什么下面的代码有效吗?

<div></div>
<div></div>​

var arr = ['foo', 'bar', 'bar'];

$.each(arr, function(i, value){
    $('div').eq(0).append(value + ' ');
});

$.each($.unique(arr), function(i, value){
    $('div').eq(1).append(value  + ' ');
});
​

http://jsfiddle.net/essX2/

http://jsfiddle.net/essX2/

Thanks

谢谢

Edit: Possible solution:

编辑:可能解决方案:

function unique(arr) {
var i,
    len = arr.length,
    out = [],
    obj = { };

for (i = 0; i < len; i++) {
    obj[arr[i]] = 0;
}
for (i in obj) {
    out.push(i);
}
return out;
};

7 个解决方案

#1


22  

It might work on an array strings, etc, but it has not been designed for that use...

它可能适用于数组字符串等,但它并不是为那种用途而设计的......

Notice that the code for unique() is hiding in Sizzle as uniqueSort: github source

请注意,unique()的代码隐藏在Sizzle中作为uniqueSort:github源

While some of that extra code might seem like it would work on any array, pay close attention to sortOrder as defined here. It does a lot of extra work to put things in "document order" - hence why the documentation states that it should only be used on arrays of DOM elements.

虽然一些额外的代码似乎可以在任何数组上工作,但请密切关注此处定义的sortOrder。将内容置于“文档顺序”中会做很多额外的工作 - 因此文档说明它应该仅用于DOM元素的数组。

#2


82  

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 :

虽然它有效,但您应该考虑功能描述。如果创建者说它不是为过滤dom元素以外的任何数组而设计的,那么你应该听听它们。此外,这个功能很容易被复制:

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 :

为了使这段代码能够在所有浏览器中工作(包括不支持某些数组功能的ie7,例如indexOf或filter),这里使用jquery功能进行重写:

  • use $.grep instead of Array.filter
  • 使用$ .grep而不是Array.filter
  • use $.inArray instead of Array.indexOf
  • 使用$ .inArray而不是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)

(演示页)

#3


6  

If not limited using jQuery, consider to use Set from ES6.

如果不限制使用jQuery,请考虑使用ES6中的Set。

var arr = ['foo', 'bar', 'bar'];
Array.from(new Set(arr)); // #=> ["foo", "bar"]

Working for Firefox 45, Safari 9 and Chrome 49.

适用于Firefox 45,Safari 9和Chrome 49。

#4


5  

I know unique works with DOM but this WORKS on arrays of int:

我知道DOM的独特作用,但这在int数组上工作:

$.unique(arr.sort());

#5


3  

$.unique will remove duplicate DOM elements, not identical DOM elements. When you try to use it on strings, you get unpredictable behavior and the sorting will (probably) fail.

$ .unique将删除重复的DOM元素,而不是相同的DOM元素。当您尝试在字符串上使用它时,您会得到不可预测的行为,并且排序将(可能)失败。

It's a function intended for internal use by jQuery only, and won't be useful to mere mortals like you and I.

它是一个仅供jQuery内部使用的功能,对你和我这样的凡人都没用。

#6


2  

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

有一种快速方法可以扩展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);

// 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

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

#7


0  

$.unique will only remove duplicate DOM element, if you need it for array :

$ .unique只会删除重复的DOM元素,如果你需要它的数组:

var result=[] ;
$.each([12,1,2,4,3,1,4,3,3,2,111], 
        function(i,e){ if($.inArray(e,result)===-1) result.push(e) ;});
result;

#1


22  

It might work on an array strings, etc, but it has not been designed for that use...

它可能适用于数组字符串等,但它并不是为那种用途而设计的......

Notice that the code for unique() is hiding in Sizzle as uniqueSort: github source

请注意,unique()的代码隐藏在Sizzle中作为uniqueSort:github源

While some of that extra code might seem like it would work on any array, pay close attention to sortOrder as defined here. It does a lot of extra work to put things in "document order" - hence why the documentation states that it should only be used on arrays of DOM elements.

虽然一些额外的代码似乎可以在任何数组上工作,但请密切关注此处定义的sortOrder。将内容置于“文档顺序”中会做很多额外的工作 - 因此文档说明它应该仅用于DOM元素的数组。

#2


82  

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 :

虽然它有效,但您应该考虑功能描述。如果创建者说它不是为过滤dom元素以外的任何数组而设计的,那么你应该听听它们。此外,这个功能很容易被复制:

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 :

为了使这段代码能够在所有浏览器中工作(包括不支持某些数组功能的ie7,例如indexOf或filter),这里使用jquery功能进行重写:

  • use $.grep instead of Array.filter
  • 使用$ .grep而不是Array.filter
  • use $.inArray instead of Array.indexOf
  • 使用$ .inArray而不是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)

(演示页)

#3


6  

If not limited using jQuery, consider to use Set from ES6.

如果不限制使用jQuery,请考虑使用ES6中的Set。

var arr = ['foo', 'bar', 'bar'];
Array.from(new Set(arr)); // #=> ["foo", "bar"]

Working for Firefox 45, Safari 9 and Chrome 49.

适用于Firefox 45,Safari 9和Chrome 49。

#4


5  

I know unique works with DOM but this WORKS on arrays of int:

我知道DOM的独特作用,但这在int数组上工作:

$.unique(arr.sort());

#5


3  

$.unique will remove duplicate DOM elements, not identical DOM elements. When you try to use it on strings, you get unpredictable behavior and the sorting will (probably) fail.

$ .unique将删除重复的DOM元素,而不是相同的DOM元素。当您尝试在字符串上使用它时,您会得到不可预测的行为,并且排序将(可能)失败。

It's a function intended for internal use by jQuery only, and won't be useful to mere mortals like you and I.

它是一个仅供jQuery内部使用的功能,对你和我这样的凡人都没用。

#6


2  

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

有一种快速方法可以扩展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);

// 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

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

#7


0  

$.unique will only remove duplicate DOM element, if you need it for array :

$ .unique只会删除重复的DOM元素,如果你需要它的数组:

var result=[] ;
$.each([12,1,2,4,3,1,4,3,3,2,111], 
        function(i,e){ if($.inArray(e,result)===-1) result.push(e) ;});
result;