Tuesday, 29 November 2011

How to create an unique array using javascript

Array.prototype.indexOf = function(e){
    for (var i = 0; i < this.length; i++) {
        if (e==this[i]) {
            return i;
        }
    }

  return -1;
}

Array.prototype.unique = function () {
    var values = this;
    var uniqueValues = [];
    for (var i = values.length; i--;) {
        var val = values[i];
        if (uniqueValues.indexOf(val) === -1) {
            uniqueValues.unshift(val);
        }
    }
    return uniqueValues;
};

No comments:

Post a Comment