jQuery.unique() in jQuery

jQuery.unique( array ) : Create a copy of an array of DOM elements with the duplicates removed. 
 Note that this only works on arrays of DOM elements, not strings or number

The $.unique() function searches through an array of objects, forming a new array that does not contain duplicate objects. This function only works on plain JavaScript arrays of DOM elements, and is chiefly used internally by jQuery.

Removes any duplicate elements from the array of divs.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; }
  </style>
  <script src="/scripts/jquery-1.4.js"></script>
</head>
<body>
	<div>There are 6 divs in this document.</div>
  <div></div>
  <div class="dup"></div>
  <div class="dup"></div>

  <div class="dup"></div>
  <div></div>
<script>

    var divs = $("div").get(); // unique() must take a native array

    // add 3 elements of class dup too (they are divs)
    divs = divs.concat($(".dup").get());
    $("div:eq(1)").text("Pre-unique there are " + divs.length + " elements.");

    divs = jQuery.unique(divs);
    $("div:eq(2)").text("Post-unique there are " + divs.length + " elements.")
                  .css("color", "red");

</script>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *