1 双重for循环
function distinct(value) { let arr = value; for (let i=0, len=arr.length; i<len; i++) { for (let j=i+1; j<len; j++) { if (arr[i] == arr[j]) { arr.splice(j, 1); // splice 会改变数组长度,所以要将数组长度 len 和下标 j 减一 len--; j--; } } } return arr } var arrlist = [1, 3, 5, 3, 5, 6, 7] var dealArr = distinct(arrlist) console.log(dealArr) // 此性能最差
2 Array.filter() + indexOf
function distinct(value) { let arr = value; return arr.filter((item, index)=> { return arr.indexOf(item) === index }) } var arrlist = ['ab', 'cd', 'ab', 6, 5, 6, 7] var dealArr = distinct(arrlist) console.log(dealArr) // 此性能较差
3 ES6 Set
var arr = [1, 2, 4, 4, 6, 6, 8] let tempArr = new Set(arr) let dealArr = Array.from(tempArr) console.log(dealArr) // 性能优
4 Array.sort()
function distinct(value) { let arr = value arr = arr.sort() let result = [arr[0]] for (let i=1, len=arr.length; i<len; i++) { arr[i] !== arr[i-1] && result.push(arr[i]) } return result } var arrlist = ['ab', 'cd', 'ab', 6, 5, 6, 7] var dealArr = distinct(arrlist) console.log(dealArr) // 此性能比较优秀
5 for...of + Object
function distinct(value) { // 利用对象的属性不会重复这一特性,校验数组元素是否重复 let arr = value let result = [] let obj = {} for (let i of arr) { if (!obj[i]) { result.push(i) obj[i] = 1 } } return result } var arrlist = ['ab', 'cd', 'ab', 6, 5, 6, 7] var dealArr = distinct(arrlist) console.log(dealArr) // 此性能最优