1.将数组里的值拿进空数组,拿进去的时候判断是否与空数组相等,相等就继续下一项,不相等就push进新数组 不修改原数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var aaa = [5,2,6,4,2,2,7,3,34,56,23,4]; var arr = []; for (let i = 0; i < aaa.length; i++) { flg = true; for (let j = 0; j < arr.length; j++) { if (arr[j] === aaa[i]) { flg = false; i += 1; break; }else{ flg = true; } } if (flg) { arr.push(aaa[i]) } } console.log(arr); |
2.拿当前项跟剩余项作比较;如果有相等就截取点这个数,并结束循环令i-1重新从这一项开始检查 直接修改原数组
1 2 3 4 5 6 7 8 9 10 |
for(let i = 0; i < aaa.length; i++){ for(let j = i + 1; j < aaa.length; j++){ if(aaa[i] === aaa[j]){ aaa.splice(j,1); i -= 1; break } } } console.log(aaa); |
1 2 3 4 5 6 7 8 |
var bbb = [2,1,4,4,23,23,523,3,57,7,2,1,56]; for(let i = 0; i < bbb.length; i++){ if(bbb.indexOf(bbb[i]) !== i){ bbb.splice(i,1) i-=1; }; } console.log(bbb); |
1 2 3 4 5 6 7 8 |
var ccc1 = ccc.sort(function(a,b){if (ab) { return 1}}) for(let i = 0; i < ccc1.length; i++){ if(ccc1[i] === ccc1[i+1]){ ccc1.splice(i,1); i -= 1 } } console.log(ccc1); |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var ccc = [2,3,1,2,4,4,5,43,2,42,54,9]; function deduplication(){ var arr = [],obj = {}; for(let i = 0; i < ccc.length; i++){ var str = ccc[i]; if (!obj[str]) { arr.push(str); } obj[str] = true; } return arr; } console.log(deduplication()); |
1 2 3 |
var ddd = [2,3,1,1,1,3,4,56,4,3,2,6]; var ddd1 = [...new Set(ddd)]; console.log(ddd1); |