Javascript 如何使用jquery查找数组中的重复项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4346547/
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
How to find the duplicates in an array using jquery
提问by kumar
I have a jQuery array:
我有一个 jQuery 数组:
var arr = $('input[name$="recordset"]');
I am getting the value of array like 8 or 6
我得到像 8 或 6 这样的数组的值
If array values are repeating or duplicate I need to show "please do not repeat the values". If not I need to proceed further.
如果数组值重复或重复,我需要显示“请不要重复值”。如果不是,我需要进一步进行。
Using jQuery can anybody tell me how to find the duplicate values?
使用 jQuery 谁能告诉我如何找到重复的值?
回答by Sean Vieira
var unique_values = {};
var list_of_values = [];
$('input[name$="recordset"]').
each(function(item) {
if ( ! unique_values[item.value] ) {
unique_values[item.value] = true;
list_of_values.push(item.value);
} else {
// We have duplicate values!
}
});
What we're doing is creating a hash to list values we've already seen, and a list to store all of the unique values. For every input the selector returns we're checking to see if we've already seen the value, and if not we're adding it to our list andadding it to our hash of already-seen-values.
我们正在做的是创建一个散列来列出我们已经看到的值,以及一个存储所有唯一值的列表。对于选择器返回的每个输入,我们都会检查是否已经看到该值,如果没有,我们将它添加到我们的列表中,并将它添加到我们已经看到的值的哈希中。
回答by Senthil
Hope that below snippets will help if someone looks for this kind of requirement
希望如果有人寻找这种要求,下面的片段会有所帮助
var recordSetValues = $('input[name$="recordset"]').map(function () {
return this.value;
}).get();
var recordSetUniqueValues = recordSetValues.filter(function (itm, i, a) {
return i == a.indexOf(itm);
});
if (recordSetValues .length > recordSetUniqueValues.length)
{ alert("duplicate resource") }
回答by Needhi Agrawal
$('form').submit(function(e) {
var values = $('input[name="recordset[]"]').map(function() {
return this.value;
}).toArray();
var hasDups = !values.every(function(v,i) {
return values.indexOf(v) == i;
});
if(hasDups){
// having duplicate values
alert("please do not repeat the values");
e.preventDefault();
}
});
回答by Thiago Belem
// For every input, try to find other inputs with the same value
$('input[name$="recordset"]').each(function() {
if ($('input[name$="recordset"][value="' + $(this).val() + '"]').size() > 1)
alert('Duplicate: ' + $(this).val());
});