// 获得去重之后的数组 Array.prototype.noRepeat = function () { return [...new Set(this)]; }
// 被删除的重复条目的新数组 Array.prototype.getRepeat = function () { let noRepeat = new Set(this.noRepeat()); return this.filter((x) => { !noRepeat.has(x) }) }
let arr1 = [1,2,3,4,5,4,3,2]; let arr2 = ['a','b','c','d','e','d','c']; let arr1_0 = arr1.noRepeat() let arr1_1 = arr1.getRepeat() let arr2_0 = arr2.noRepeat() let arr2_1 = arr2.getRepeat()
Array.prototype.repeat=function(){ let arr=this,arr1=[],obj={}; for(let i=0;i<arr.length;++i){ if(!obj[arr[i]]){ obj[arr[i]]=true; }else{ arr1.push(arr[i]); } } return arr1; };
Array.prototype.deleteSame=function(){ var arr=this; var a=[]; for (var i=0;i<this.length;i++){ var index=a.indexOf(arr[i]); //console.log(index); if(index==-1){ a.push(arr[i]); arr.splice(i,1);//删除后会自动往前移动所以i-1 i--; } else{ continue; } } return a; } var test=[1,2,3,3,4,5,9,3,4,6]; console.log(test.deleteSame());
Array.prototype.deleteSame = function(){ let mySet = new Set(), //用集合天然去重 a = []; this.forEach( function(item) { if (!mySet.has(item)) { //没有则加入集合 mySet.add(item); } else { a.push(item) //有则加入数组 } }); return a; }; console.log([1,NaN2,1,2, NaN, NaN].deleteSame()) //[1, 2, NaN] 可以去NaN 不能去对象 //哇 缩进搞了我好久
Array.prototype.respeat = function(){ var a = []; var arr = this; arr.forEach(function(v,i) { if(i !== arr.lastIndexOf(v) && i==arr.indexOf(v)) { a.push(v); } }) return a; }
}