Get Unique Element In Array | JQuery

Get Unique Element In Array | JQuery

Added by Nasir Mahmood updated on Friday, November 17, 2017

Problem:

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

Related Tags

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected