Javascript Array unique2()

Description

Javascript Array unique2()


Array.prototype.unique2 = function(){
 this.sort(); /*from  www .ja  va2 s. c om*/
 var res = [this[0]];
 for(var i = 1; i < this.length; i++){
  if(this[i] !== res[res.length - 1]){
   res.push(this[i]);
  }
 }
 return res;

alert(arr.unique2());

Javascript Array unique2()

var arr=[1,2,2,3,4,5,6,7,7,6,5,4,4,3];

Array.prototype.unique2=function(){
 var _this=this;//from ww  w.  j a v a2s.c o  m
 var obj={};
 var newArr=[];
 for(var i=0;i<_this.length;i++){
  if(!obj[arr[i]]){
   newArr.push(arr[i]);
   obj[arr[i]]=1;
  }
 }
 return newArr;
}
arr.unique2();

Javascript Array unique2()

var numbers = [4, 5, 4 , 4, 5, 4, 5]

function unique(arr) {
    var newArr = [];
    for (var i = 0; i < arr.length; i++){
        if (newArr.indexOf(arr[i]) < 0 ){
            newArr.push(arr[i]);/*from   w w w  .ja  va2s  .co  m*/
        }
    }
    return newArr;
}
console.log(unique(numbers));

var unique1 = function (arr){
    return arr.filter(function(x,i) {
        return arr.indexOf(x) === i
    })
}

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

Javascript Array unique2()

Array.prototype.unique2 = function () {
  var a = [],/*from w  w  w. j  a va2s  .c  o  m*/
    n = this.length;
    for (var i=0; i<n; ++i) {
      for (var j=i+1; j<n; ++j) {
        if(this[i]===this[j]) j = ++i;
      }
      a.push(this[i]);
    }
  return a;
};

Javascript Array unique2()

Array.prototype.unique2 = function(){
 this.sort(); //from www .  j a  v  a2 s.  c o m
 var res = [this[0]];
 for(var i = 1; i < this.length; i++){
  if(this[i] !== res[res.length - 1]){
   res.push(this[i]);
  }
 }
 return res;
}
var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, 0]
alert(arr.unique2());

Array.prototype.unique3 = function(){
 var res = [];
 var json = {};
 for(var i = 0; i < this.length; i++){
  if(!json[this[i]]){
   res.push(this[i]);
   json[this[i]] = 1;
  }
 }
 return res;
}

Javascript Array unique2()


Array.prototype.unique2=function () {
    var n={};/*from ww w. j  a v  a  2 s.co  m*/
    var tmp=[];

    for(var i=0;i<this.length;i++){
        if(!n[this[i]]){
            n[this[i]]=true;
            tmp.push(this[i]);
        }
    }
    return tmp;
}



PreviousNext

Related