Saturday, July 11, 2015

Get Unique Element In Array | JQuery

Since Jquery does not provide function to get unique elements from array. Although it has $.unique() function but according to documentation “This function only works on plain JavaScript arrays of DOM elements”.
Following is small javascript function which return unique elements from input array.

       function unique( array ) {
                                             return $.grep( array, function ( element, index ) {
                                                                  return index == $.inArray( element, array );
                                                                } );
                                          }


Usage:
var array_data = [];
array_data.push( 1 );
array_data.push( 2 );
array_data.push( 3 );
array_data.push( 2 );
array_data.push( 3 );
array_data.push( 4 );
array_data.push( 5 );


array_data = unique( array_data );

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More