Thursday, April 8, 2010

Algorithm for unique array, optimized

I had come across a scenario where the need was to have an array with unique values.
Algorithm for small size array would not matter much in term of performance, but for large arrays the algorithm needs to be quick as it could become time consuming and can really affect browser performance.

Syntax:
Array.unique()

This function will return a new array with all values unique.

Example:
var arr = new Array(1,5,3,6,2,6,8,9,8,3);
arr.unique();
// Output will be (1,2,3,5,6,8,9)

Function:
Array.prototype.unique = function() {
    this.sort();
    var r = new Array();
    o:for(var i=0,n=this.length;i<n;i++){
        for(var x=r.length-1,y=x+1;x<y;x++){
            if(r[x]==this[i]) continue o;
        }
        r[r.length]=this[i];
    }
    return r;
};