ドキュメント

Utilities/jQuery.unique

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Utilities

jQuery.unique( array )

Remove all duplicate elements from an array of elements. Note that this only works on arrays of DOM elements, not strings or numbers.
Arguments:
arrayArray
The Array of Elements to translate.
Examples:

Removes any duplicate elements from the array of divs.

    var divs = $("div").get();

    // 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");

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    var divs = $("div").get();

    // 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>
  <style>
  div { color:blue; }
  </style>
</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>
</body>
</html>

Removes any duplicate elements from the array of divs.

$.unique(document.getElementsByTagName("div"));

[<div>, <div>, ...]

NameType