首页 > 试题广场 >

数组去重

[编程题]数组去重
  • 热度指数:77814 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
为 Array 对象添加一个去除重复项的方法
示例1

输入

[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN]

输出

[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a']
// By ClayIdols
//生成器
Array.prototype.uniq = function () {
    var hasNaN = false;
    for(i=0;i<this.length;i++){
        for(j=i-1;j>=0;j--){
            if((this[i] === this[j]) || (hasNaN && this[i]!==this[i])){
                this.splice(i,1);
            }
        }
        if(!hasNaN && this[i]!==this[i]){
                hasNaN = true;
        } 
    }
}
x = [false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN];
console.log(x);
x.uniq();
console.log(x);


编辑于 2015-07-01 23:35:30 回复(2)
主要是去除NaN   (      NaN==NaN // false;  NaN===NaN     // false)

发表于 2016-07-21 21:55:14 回复(0)
        理解了如何去除NaN属性的值就很容易了
        Array.prototype.uniq = function () {
            let arr = [];
            let flag = true;
            for (let i = 0; i < this.length; i++) {
                if (arr.indexOf(this[i]) == -1) { //判断arr数组有没有这个元素
                    if ((this[i] != this[i]) && (typeof this[i] == 'number')) {
                        //这个条件主要判断是不是NaN属性的 添加过一次NaN属性后if就不可能在执行了
                        if (flag) {
                            arr.push(this[i]);
                            flag = !flag
                        }
                    } else {
                        arr.push(this[i])
                    }
                }
            }
            return arr
        }

发表于 2022-04-20 15:24:16 回复(0)
function bindThis(f, oTarget) {
    return function() {
        return f.apply(oTarget, arguments);
    }
}

Array.prototype.uniq = function () {
    return [...new Set(this)];
}

发表于 2022-03-26 16:55:51 回复(0)
Array.prototype.uniq = function () {
    return [...new Set(this)];
}

发表于 2021-07-28 13:56:46 回复(0)
Array.prototype.uniq = function () {
  let resArr = []
  let hasNaN = false
  let len = this.length
  for (let i = 0; i < len; i++) {
    let val = this[i]
    if (resArr.indexOf(val) === -1) {
      if (!(typeof val === 'number' && isNaN(val))) {
        resArr.push(val)
      } else {
        if (!hasNaN) {
          hasNaN = true
          resArr.push(val)
        }
      }
    }
  }
  return resArr
}

发表于 2021-07-05 23:15:27 回复(0)
    Array.prototype.uniq = function () {
    let arr = this, length = this.length, hash = {}, res = []
    for (let i = 0; i < length; i++) {
        if (!hash[arr[i]] || /Object/.test(Object.prototype.toString.call(arr[i]))) {
            res.push(arr[i])
            hash[arr[i]] = 1
        }
    }
    return res
  }


感觉没什么毛病吧这个写法,为什么通过率只有75%?

发表于 2020-04-04 19:09:07 回复(0)
/***
 * 
 * ES6  使用集合直接进行去重操作
    function unique(arr){
      return [...new Set(arr)];
  }
 */
Array.prototype.uniq = function () {
    //1. 定义一个数组  和  标志位
    let finalArr = [];
    let flag = true;
    // for循环操作
    for (let i = 0; i < this.length; i++) {
        // 使用indexOf方法  如果要检索的字符串值没有出现,则该方法返回 -1
        if (finalArr.indexOf(this[i]) == -1) {
            if (this[i] != this[i]) { //排除 NaN
                if (flag) {
                    // 加入去重数组中
                    finalArr.push(this[i]);
                    // 改变标志位
                    flag = false;
                }
            } else {
                //直接进行 push操作
                finalArr.push(this[i]);
            }
        }
    }
    return finalArr;
}

发表于 2020-03-08 11:59:39 回复(0)
Array.prototype.uniq = function () {
    return this.reduce((prev, next) => {
        prev.findIndex(item => Object.is(item, next)) === -1 && prev.push(next);
        return prev;
    }, [])
}
通过Object.is判断即可
发表于 2019-09-30 11:36:38 回复(0)
Array.prototype.uniq = function () {
    var hasNaN = false;
    for (var i = 0; i < this.length; i++) {
        if ((hasNaN === false) && (this[i] != this[i])) {
            hasNaN = true;
            continue;
        }
        if (this.indexOf(this[i]) < i) this.splice(i--,1);
    }
    return this;
}

发表于 2018-09-20 15:50:51 回复(0)
Array.prototype.uniq = function () {
    var arr=this,result=[];
    for(var i=0;i<arr.length;i++){
        if(i==0){
            result.push(arr[i]);
        }else{
            for(var j=0;j<result.length;j++){
              if(isNaN(arr[i])&&typeof(arr[i])==="number"){//第一层先判断是否是NaN
                if(isNaN(result[j])&&typeof(arr[j])==="number"){
                  break;
                }else if(j==result.length-1){
                  result.push(arr[i]); 
                }
              }else{//当当前值不是NaN时
                if(result[j]===arr[i]){
                    break;
                }else if(j==result.length-1){
                    result.push(arr[i]);
                }
              } 
            }
        }
    }
    return result;
}
发表于 2018-09-10 23:16:25 回复(0)
// 为什么这样写不通过
Array.prototype.uniq = function() {
    return this.filter(function(ele,index,arr){
        return index === arr.indexOf(ele);
    });
};
发表于 2018-07-24 11:03:56 回复(1)
Array.prototype.uniq = function () {
    var len = this.length;
    for (var i = 0; i < len; i++) {
        for (var j = i + 1; j < len; j++) {
         // 判断通常情况,{}==={}的判断只会判断引用地址是否一致,相同才会过滤掉
            if (this[i] === this[j]) {
                this.splice(j--, 1);
                len--;
         // 下一行语句判断NaN的情况
            } else if (this[i] != this[i] && this[j] != this[j]) {
                this.splice(j--, 1);
                len--;
            }
        }
    }
    return this;
};
本来可以用Number.isNaN()来判断,然而牛客不给通过,不支持ES6,就不用ES6写法了。
编辑于 2018-07-06 17:42:48 回复(0)
Array.prototype.uniq = function () {
    return [...new Set(this)]
}
这样为什么不算过=.=
发表于 2018-01-31 19:35:45 回复(2)
Array.prototype.uniq = function () {
 var arr = [];
 var flag = true;
 this.forEach(function(item) {
 // 排除 NaN (重要!!!)
 if (item != item) {
 flag && arr.indexOf(item) === -1 ? arr.push(item) : '';//push这个地方一定要与后面的冒号之间有空格否则会出错
 flag = false;
 } else {
 arr.indexOf(item) === -1 ? arr.push(item) : ''
 }
 });
 return arr;
}
发表于 2017-08-16 19:45:33 回复(0)
//删除,改变数组,不用返回删除的数,测试数组中有NaN,要把重复的NaN删除
//一次循环
Array.prototype.uniq = function () {
var flag=true;
	for(var i=0; i<this.length;){
		if(this.indexOf(this[i]) !== i){ //包括重复的和NaN
			if(this[i] !== this[i]){ //为NaN
				if(flag){flag = !flag;//第一个NaN
                                         i++;
				} else{this.splice(i,1);}//重复的NaN
			}else{this.splice(i,1);} //除NaN后重复的
		}else{i++;}//不重复的
	}
return this;
}

编辑于 2017-03-13 17:15:37 回复(1)
Array.prototype.uniq = function () {
    var flag=true;
    return this.filter(function(item,index,array){
        if(item!=item&&flag){
            array.splice(index,1,item);
            flag=false;
            return index !=array.indexOf(item);
        }else{
            return index ===array.indexOf(item);
        } 
    });
};
 这题真难,但是写出来的代码简单易看才是***的!!!!

发表于 2017-02-20 03:56:35 回复(0)
Array.prototype.uniq = function () {
    var obj = {},newArr = [],item = null,key = null;
    for (var i = 0; i < this.length; i++) {
        item = this[i];
		var type = Object.prototype.toString.call(null).replace(/\[|\]/g,"").split(" ")[1];
		var key = type+item;
       // key = typeof this[i] + item;
       //过滤出Object
        if(!obj[key] || key.indexOf("object")>-1){
            newArr.push(item);
            obj[key] = true;
        }
    }
    return newArr;
}
[false, true, undefined, null,null,new Date(),new Date(),NaN, 0, 1, {}, {}, 'a', 'a', NaN].uniq();
编辑于 2017-02-19 18:05:25 回复(2)
Array.prototype.uniq = function () {
  var gotFirstNaN = false
  var gotFirstEmptyObj = false
  return this.filter(function(val,idx,arr){
    // 处理 NaN 的情况
    if (!val && isNaN(val) && val !== undefined && !gotFirstNaN ) {
      gotFirstNaN = true
      return true
    }
    // 处理 {} 的情况 (题目未要求,删除这段可AC)
    else if (val instanceof Object && !val.getOwnPropertyNames){
      if (!gotFirstEmptyObj) {
        gotFirstEmptyObj = true
        return true
      }
      return false
    }
    // 处理一般情况
    return arr.indexOf(val) === idx
  });
}
var a = [false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN].uniq()
console.log(a)

发表于 2016-09-06 14:59:09 回复(0)
我发现这个在本地测试,{}始终去重不了,由于({}!={}这个判断进不去),把前面获取的代码拿来测试后也是一样的。我的代码也提交成功了。但是考虑还是不全面
Array.prototype.uniq = function () {
    var result=[];
    var pushedNaN=false;
    var pushednullobj=false;
    for(var i =0;i<this.length;i++){
        var index1=this.indexOf(this[i]);
        var index2=this.lastIndexOf(this[i]);
        if(index1!=index2){
            result.push(this[i]);
            while(index1!=this.lastIndexOf(this[i])){
                this.splice(this.lastIndexOf(this[i]),1);
            }
        }else if(index1==-1){//针对NaN做的判断,只有第一次出现的NaN能够push进result
            if(!pushedNaN){
                result.push(this[i]);
                pushedNaN=true;
            }
        }else if(this[i]!=this[i]){//针对{}做的判断,本地测试时没起作用,且如果是两个不同的对象,则这个地方所做处理不对。需要增加判断对象属性及值的机制。但是估计这个测试用例没考虑{}
            if(!pushednullobj){
                result.push(this[i]);
                pushednullobj=true;           
            }
        }else{
            result.push(this[i]);
        }
    }
    return result;
}

发表于 2016-08-16 17:21:59 回复(4)