removes duplicate elements from an array

Description

$.unique() removes duplicate elements from an array of DOM elements.

Example


<!DOCTYPE html>
<html>
  <head>
  </head><!--from w  ww. j  a  v a2s .  c o m-->
  <body>
    <p></p>
    <p></p>
    <p></p>
    <p class="duplicate"></p>
    <p class="duplicate"></p>
    <p class="duplicate"></p>
    <p></p>  
    <script 
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
    </script>
    <script>     
      $(document).ready(function(){
          // select all paragraph elements
          var paragraphs = $( "p" ); 
          
          //returns 7
          console.log( paragraphs.length );
       
          //turn it into an array
 
          paragraphs = $.makeArray( paragraphs );
          
          //get elements of class duplicate and immediately convert them to an array
          var dupes = $.makeArray($( ".duplicate" ))
 
          //concat them into our paragraphs array 
          paragraphs = paragraphs.concat( dupes );
          
          //returns 10
          console.log( paragraphs.length );
          
          //get rid of the dupes
          paragraphs = $.unique( paragraphs );
          
          //returns 7
          console.log( paragraphs.length );
          
          var index = $.inArray("6", paragraphs);
          console.log(index); // returns -1
      });
    </script>
 
  </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities