1.ES6 Set
let arr = [1,2,3,3,"a","a","1"] arr = [...new Set(arr)] console.log(arr) // [1, 2, 3, "a", "1"]
2.indexOf
let arr = [1,2,3,3,"a","a","1"] function unique(array){ if (!Array.isArray(arr)) { console.log('type error!') return } let temp = []; for(let i = 0; i < array.length; i++){ if(temp.indexOf(array[i]) == -1){ temp.push(array[i]); } } return temp; } console.log(unique(arr)) // [1, 2, 3, "a", "1"]
3.sort
let arr = [1,2,3,3,"a","a","1"] function unique(array){ if (!Array.isArray(arr)) { console.log('type error!') return } array.sort(); let temp = [array[0]]; for(let i = 0; i < array.length; i++){ if(array[i] !== temp[temp.length-1]){ temp.push(array[i]); } } return temp; } console.log(unique(arr)) // [1, 2, 3, "a", "1"]
4.for循环
let arr = [1,2,3,3,"a","a","1"] function unique(array){ if (!Array.isArray(arr)) { console.log('type error!') return } let temp = []; for(let i = 0; i < array.length; i++) { for(let j = i + 1; j <array.length; j++){ if (array[i] === array[j]){ i++; j = i; } } temp.push(array[i]); } return temp; } console.log(unique(arr)) // [1, 2, 3, "a", "1"]
5.includes
let arr = [1,2,3,3,"a","a","1"] function unique(array){ if (!Array.isArray(arr)) { console.log('type error!') return } let temp = []; for(let i = 0; i < array.length; i++) { if(!temp.includes(array[i])){ temp.push(array[i]); } } return temp; } console.log(unique(arr)) // [1, 2, 3, "a", "1"]
6.对象
let arr = [1,2,3,3,"a","a","1"] // 判断是否为js对象键时,会自动对传入的键执行“toString()” function unique(array){ if (!Array.isArray(arr)) { console.log('type error!') return } let temp = {}, temp1 = [], val, type; for (let i = 0; i < array.length; i++) { val = array[i]; type = typeof val; if (!temp[val]) { temp[val] = [type]; temp1.push(val); } else if (temp[val].indexOf(type) < 0) { temp[val].push(type); temp1.push(val); } } return temp1; } console.log(unique(arr)) // [1, 2, 3, "a", "1"]
7.ndexOf与下标
let arr = [1,2,3,3,"a","a","1"] function unique(array){ if (!Array.isArray(arr)) { console.log('type error!') return } let temp = []; for(let i = 0; i < array.length; i++) { if(array.indexOf(array[i]) == i){ temp.push(array[i]) } } return temp; } console.log(unique(arr)) // [1, 2, 3, "a", "1"]