Array.prototype.distinct = function() { var delArr = [], i, j, target, // 用于缓存比对基准值 hasPushed; // 标识:判断是否已被压入到返回的数组 // 仿照冒泡排序进行遍历 for (i = 0; i < this.length; i++) { target = this[i]; // 缓存比对基准值 hasPushed = false; // 重置标识 for (j = i + 1; j < this.length; j++) { if (this[j] === target) { this.splice(j, 1); // 最为关键的一步!上述操作导致数组长度减少1,因此需要在原基础上再执行一次循环 j--; if (!hasPushed) { delArr.push(target); hasPushed = true; } } } } return delArr; }; var arr = [1, 1, 2, 3, 3, 4, 2, 3, 2, 1, 2, 5, 5, 3]; var newArr = arr.distinct(); console.log(arr); // [1, 2, 3, 4, 5] // 如果上面没有 j--,那么输出 arr => [1, 2, 3, 4, 2, 5] console.log(newArr); // [1, 2, 3, 5]
Array.prototype.removeRepeat = function() { let result = [], map = {}, val; for (let i=0;i<this.length;i++) { val = this[i]; if (map[val]) { result.push(this.splice(i--, 1)[0]); //去除了这个索引的值,回退1 } else map[val] = true; } return result; }
Array.prototype.outrepeat = function() { const result = [] // 利用set去重 const setArr = new Set(this) // 判断重复元素,并推送至result数组 for(let item of setArr) { let count = 0 this.forEach(element => { item === element && count++ }) count >=2 && result.push(item) } // 修改原数组为setArr this.splice(0, this.length, ...Array.from(setArr)) return result }
来个有创意的:利用一次循环,对象属性唯一的原则实现 Array.prototype.distinct =function() { var obj = {}; for( var i=0; i<= Math.ceil(this.length/2); i++ ){ if( this.indexOf(arry[i]) != arry.lastIndexOf(arry[i]) ){ obj[this[i]] = true; } } return Object.keys(obj); } // Test var arry = [1, 2, 'q', 1, 3, '1', 'q', 3, 1]; console.log(arry.distinct()); // ["1", "3", "q"]
Array.prototype.delRepeat = function () { var result = []; var i, len = this.length, delarr=[]; for(i = 0;i<len;i++){ if(result.indexOf(this[i])===-1){ result.push(this[i]); }else{ delarr.push(this[i]); console.log('del '+i+':'+this[i]); this.splice(i,1); i--; len--; } } return delarr; }
Array.prototype.distinct = function() { var tmpArray = []; var tmpCount = 0; for (var i = 0; i < this.length; i++) { tmpCount = 0; for (var j = i + 1; j < this.length; j++) { if (this[i] === this[j]) { tmpCount += 1; } } if (!tmpCount) { tmpArray.push(this[i]); } } return tmpArray; } var testArray= [1,1,2,2,3,3,3,31,1,4,4,9]; console.log('before:',abcde); console.log('after:',abcde.distinct());