原文来自:https://juejin.im/post/5ba6e77e6fb9a05d0b14359b
<script> let str = "12qwe345671dsfa233dsf9876ds243dsaljhkjfzxcxzvdsf"; let array = str.split(""); //方案一: array = [...new Set(array)].join(""); array = ((a)=>[...new Set(a)])(array).join(""); console.log(array);//12qwe34567dsfa98ljhkzxcv 只能过滤,不会统计 //方案二: function unique (arr) { const seen = new Map() return (arr.filter((a) => !seen.has(a) && seen.set(a, 1))).join(""); } console.log(unique(array)) // 12qwe34567dsfa98ljhkzxcv //方案三: function unique (arr) { let arrs=[]; var news_arr = arr.sort();//排序能减少一次循环 for(var i=0;i<news_arr.length;i++){ if(news_arr[i] == news_arr[i+1] && news_arr[i]!= news_arr[i-1] ){ arrs.push(arr[i]); }; }; return arrs.join(""); } console.log(unique(array)) // 12qwe34567dsfa98ljhkzxcv //方案四: function unique (arr) { let obj={}; for(var i=0;i<arr.length;i++){ let key = arr[i]; if(!obj[key] ){ obj[key]=1; }else{ obj[key]+=1; } }; return obj; } console.log(unique(array)) // object 对应每个key以及它重复的次数 </script>