js對數組裡的基礎型別和物件去重
阿新 • • 發佈:2018-12-12
1. 單元素去重
//1. 雙重迴圈去重 var array = [1, 1, '1', '1',NaN,NaN]; function unique(array) { // res用來儲存結果 var res = []; for (var i = 0, arrayLen = array.length; i < arrayLen; i++) { for (var j = 0, resLen = res.length; j < resLen; j++ ) { if (array[i] === res[j]) { break; } } // 如果array[i]是唯一的,那麼執行完迴圈,j等於resLen if (j === resLen) { res.push(array[i]) } } return res; } console.log(unique(array)); // [1, "1"] //利用indexof去重 function unique2(array){ var res1=[]; for(var i=0;i<array.length;i++){ if(res1.indexOf(array[i])===-1){ res1.push(array[i]) } } return res1 } console.log(unique2(array)) //利用indexof加filter function unique3(array){ var res=array.filter(function (item,index,array) { return array.indexOf(item)===index }) return res } array=[2,3,4,[1,2],[1,2]] console.log(unique3(array)) function unique4(array) { return Array.from(new Set(array)); } array=[2,3,4,[1,2],[1,2],NaN,NaN] console.log(unique4(array))
2. 物件去重
//去除陣列,物件 function uniqueObject(arr) { var hash = {}; var result = arr.reduce(function(item, next) { hash[next.name] ? '' : hash[next.name] = true && item.push(next); return item }, []) return result } const arr = [1,1,NaN,NaN,'1',1,'1', { name:'tom', age:15 }, { name:'jack', age:18 }, { name:'tom', age:10 }] console.log(uniqueObject(arr))
3. 數組裡的基礎型別和物件去重
Array.prototype.quc=function(){ var res=[]; var jso={}; for(var i=0;i<this.length;i++){ if (!jso[JSON.stringify(this[i])]) { res.push(this[i]); jso[JSON.stringify(this[i])]=1; }; } return res; } var s1=[{"a":10,b:20},{"a":10,b:20},{"a":60,c:30},{"f":60,d:30},1,1,1,'1','1',NaN,NaN]; console.log(s1.quc())