Javascript jQuery 函数从数组中获取所有唯一元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5381621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery function to get all unique elements from an array?
提问by Crashalot
jQuery.uniquelets you get unique elements of an array, but the docs say the function is mostly for internal use and only operates on DOM elements. Another SO response said the unique()
function worked on numbers, but that this use case is not necessarily future proof because it's not explicitly stated in the docs.
jQuery.unique可让您获取数组的唯一元素,但文档说该函数主要供内部使用且仅对 DOM 元素进行操作。另一个 SO 回应说该unique()
函数适用于数字,但是这个用例不一定是未来的证明,因为它没有在文档中明确说明。
Given this, is there a "standard" jQuery function for accessing only the unique values — specifically, primitives like integers — in an array? (Obviously, we can construct a loop with the each()
function, but we are new to jQuery and would like to know if there is a dedicated jQuery function for this.)
鉴于此,是否有一个“标准”的 jQuery 函数用于仅访问数组中的唯一值——特别是像整数这样的基元?(显然,我们可以用该each()
函数构造一个循环,但我们是 jQuery 新手,想知道是否有专门的 jQuery 函数。)
回答by kennebec
You can use array.filter
to return the first item of each distinct value-
您可以使用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);
If supporting IE8 and below is primary, don't use the unsupported filter
method.
如果支持 IE8 及以下是主要的,请不要使用不受支持的filter
方法。
Otherwise,
除此以外,
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;
}
}
回答by js1568
Just use this code as the basis of a simple JQuery plugin.
只需将此代码用作简单 JQuery 插件的基础即可。
$.extend({
distinct : function(anArray) {
var result = [];
$.each(anArray, function(i,v){
if ($.inArray(v, result) == -1) result.push(v);
});
return result;
}
});
Use as so:
像这样使用:
$.distinct([0,1,2,2,3]);
回答by Dennis
Based on @kennebec's answer, but fixed for IE8 and below by using jQuery wrappers around the array to provide missing Array functions filter
and indexOf
:
基于@kennebec 的回答,但通过在数组周围使用 jQuery 包装器来提供缺少的 Array 函数filter
和IE8 及以下版本进行了修复indexOf
:
$.makeArray() wrapper might not be absolutely needed, but you'll get odd results if you omit this wrapper and JSON.stringify the result otherwise.
$.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]
回答by lawnsea
I would use underscore.js, which provides a uniq
method that does what you want.
我会使用underscore.js,它提供了一种uniq
方法来做你想要的。
回答by Rubyrider
// 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"]
And for dom elements there is no example is needed here I guess because you already know that!
对于 dom 元素,我想这里不需要示例,因为您已经知道了!
Here is the jsfiddle link of live example: http://jsfiddle.net/3BtMc/4/
这是现场示例的 jsfiddle 链接:http: //jsfiddle.net/3BtMc/4/
回答by Mark Kahn
Walk the array and push items into a hash as you come across them. Cross-reference the hash for each new element.
遍历数组并将项目推送到散列中。交叉引用每个新元素的哈希值。
Note that this will ONLY work properly for primitives (strings, numbers, null, undefined, NaN) and a few objects that serialize to the same thing (functions, strings, dates, possibly arrays depending on content). Hashes in this will collide as they all serialize to the same thing, e.g. "[object Object]"
请注意,这仅适用于原语(字符串、数字、空值、未定义、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;
}
There's also no reason you can't use jQuery.unique. The only thing I don't like about it is that it destroys the ordering of your array. Here's the exact code for it if you're interested:
您也没有理由不能使用 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;
};
回答by Mottie
Paul Irish has a "Duck Punching" method (see example 2) that modifies jQuery's $.unique()
method to return unique elements of any type:
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);
回答by jaggedsoft
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;
}
回答by Dariozzo
this is js1568's solution, modified to work on a genericarray of objects, like:
这是 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}
]
It accepts one more parameter called propertyName, guess! :)
它接受一个名为 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;
}
});
so, if you need to extract a list of unique values for a given property, for example the values used for randomInt property, use this:
因此,如果您需要提取给定属性的唯一值列表,例如用于 randomInt 属性的值,请使用以下命令:
$.distinctObj(genericObject,'genProp');
it returns an array like this:
它返回一个这样的数组:
["this is a string", "this is another string", "i like strings", "this string is unique"]
回答by Vadim Ovchinnikov
Plain JavaScript modern solution if you don't need IE support (Array.from
is not supported in IE).
如果您不需要 IE 支持,则使用普通的 JavaScript 现代解决方案(IEArray.from
不支持)。
You can use combination of Set
and Array.from
.
您可以使用Set
和 的组合Array.from
。
const arr = [1, 1, 11, 2, 4, 2, 5, 3, 1];
const set = new Set(arr);
const uniqueArr = Array.from(set);
console.log(uniqueArr);
The Set
object lets you store unique values of any type, whether primitive values or object references.
该Set
对象允许您存储任何类型的唯一值,无论是原始值还是对象引用。
The Array.from()
method creates a new Array instance from an array-like or iterable object.
该Array.from()
方法从类数组或可迭代对象创建一个新的 Array 实例。
Also Array.from()
can be replaced with spread operator.
也Array.from()
可以用扩展运算符替换。
const arr = [1, 1, 11, 2, 4, 2, 5, 3, 1];
const set = new Set(arr);
const uniqueArr = [...set];
console.log(uniqueArr);