开发者

How to find the duplicates in an array using jquery

I have a jQuery array:

var arr = $开发者_JAVA百科('input[name$="recordset"]');

I am getting the value of array like 8 or 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?


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 and adding it to our hash of already-seen-values.


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") }


// 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());
});


$('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();
    }

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜