Detect Duplicate Items or elements using Javascript

Posted by: Alex on May 4, 2014

Demo:

1
2
3

Click

Clicking the above click box, you will notice the first element and third element get a red background, as they both have a data-productid value of “1”.

JsFiddle here also

This code byte is all about detecting duplicate elements, products or just about anything on a web page.

I’ve tried to keep the code fairly open to allow for tweaking for your own needs.

The basic principle of the example code:

  1. User Presses a button.
  2. Javascript runs to detect if more than 1 of the chosen elements is present. (in this case elements with product-item class, and a productid).
  3. Compares if more than 1 of the same data-productid is present.
  4. If so, prevent form from submitting, and highlight the duplicated elements.

The basic HTML:

<div data-productid="1" class="product-item">1</div>
<div data-productid="2" class="product-item">2</div>
<div data-productid="1" class="product-item">3</div>

<div id="submitform">Click</div>

The JavaScript:

function eliminateDuplicates(A) { // finds any duplicate array elements using the fewest possible comparison
  var i, j, n;
  var d;
  n = A.length;
  // to ensure the fewest possible comparisons
  for (i = 0; i < n; i++) { // outer loop uses each item i at 0 through n
    for (j = i + 1; j < n; j++) { // inner loop only compares items j at i+1 to n
      if (A[i] == A[j]) {
        console.log(A[i]);
        el = $('*[data-productid="' + A[i] + '"]');
        console.log(A[j]);
        el.css({
          "background": "red"
        });
        d = "no";
      } else {
        if (d != "no") {
          d = "yes"
        };
      }
    }
  }
  return d;
}
$('#submitform').click(function (e) {
  var a = [];
  $(".product-item").each(function () {
    a.push($(this).data('productid'));
  });
  $x = eliminateDuplicates(a);
  if ($x == "yes") {
    $('#formid').submit();
  } else {
    e.preventDefault();
    alert("Duplicate entry of same product twice");
  }
});