Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 554
kumar Avatar asked Dec 03 '10 14:12

kumar


People also ask

How do you check if an array contains repeated values?

function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = i+1; j < myArray. length; j++) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } return false; // means there are no duplicate values. }

How do you check value is exists in array in jQuery?

1) Using jQuery If you are someone strongly committed to using the jQuery library, you can use the . inArray( ) method. If the function finds the value, it returns the index position of the value and -1 if it doesn't.

How can check duplicate value in textbox using jQuery?

Using each() check value of inputs and if any value is duplicate add class duplicate to it.


2 Answers

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.

like image 179
Sean Vieira Avatar answered Sep 20 '22 13:09

Sean Vieira


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") }
like image 43
Senthil Avatar answered Sep 21 '22 13:09

Senthil