使用 Set 实现
Set 是一组 key 的集合,但是不存 value,里面的值唯一
缺点:API 太新,旧浏览器不支持
let array = [1,5,2,3,4,2,3,1,3,4];let set = new Set(array); // Set(5) {1, 5, 2, 3, 4}let set1 = new Set();array.forEach(x => set1.add(x));console.log(set1; // Set(5) {1, 5, 2, 3, 4})
不使用 Set 实现
方法1:
unique = (array) => {let result = [];for(let i=0; i < array.length; i++){if(result.indexOf(array[i]) === -1) {result.push(array[i]);}}return result;}
方法2:使用计数排序的思想
unique = (array) => {let hash = [];let result = [];for(let i=0;i<array.length; i++){hash[array[i]] = true;}for(let k in hash){result.push(k);}return result;}
使用 Map 实现
缺点:需要额外空间存数据,API 太新,旧浏览器不支持
unique = (array) => {let hashMap = new Map();let result = [];for (let i = 0; i < array.length; i++) {if (!hashMap.has(array[i])) {hashMap.set(array[i],1);}}for (let key of hashMap.keys()) {result.push(key);}return result;}
