jQuery API

jQuery.unique()

jQuery.unique( array ) Returns: Array

Description: Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.

  • version added: 1.1.3jQuery.unique( array )

    arrayThe Array of DOM elements.

The $.unique() function searches through an array of objects, sorting the array, and removing any duplicate nodes. This function only works on plain JavaScript arrays of DOM elements, and is chiefly used internally by jQuery.

As of jQuery 1.4 the results will always be returned in document order.

Example:

Removes any duplicate elements from the array of divs.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.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>

Demo:

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for jQuery.unique() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • MarkSa
    > $.unique([2,1,2,2])
    [2, 1, 2]

    seems like no sorting takes place
  • helpfulHand
    As it says above:"This function only works on plain JavaScript arrays of DOM elements"

    You entered an arrray of numbers rather than DOM elements.