kumar
kumar

Reputation: 2944

How to find the duplicates in an array using jquery

I have a jQuery array:

var arr = $('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?

Upvotes: 7

Views: 29675

Answers (4)

Needhi Agrawal
Needhi Agrawal

Reputation: 1326

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

});

Upvotes: 1

Senthil
Senthil

Reputation: 1609

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

Upvotes: 2

Sean Vieira
Sean Vieira

Reputation: 159905

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.

Upvotes: 14

Thiago Belem
Thiago Belem

Reputation: 7832

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

Upvotes: 1

Related Questions