Javascript Array uniqueByKey(array, key)

Description

Javascript Array uniqueByKey(array, key)


Array.prototype.uniqueByKey = function(array, key) {
 // unique = foo.uniqueByKey(bar, "key").sort();
 var r = [];//from  ww  w  .j  av a  2s  .  c om
 for(var i = 0; i < array.length; i++) {
  if(r.indexOf(array[i][key]) == -1) {
   r.push(array[i][key]);
  }
 }
 return r;
}

Array.prototype.unique = function () {
 // unique = foo.unique().sort();
    var r = [];
    for(var i = 0, n = this.length; i < n; i++) {
        if (this.lastIndexOf(this[i]) == i) r.push(this[i]);
    }
    return r;
}


function isarray(input){
 return typeof(input)=='object'&&(input instanceof Array);
}



PreviousNext

Related