// 演示代码
function unique(arr) {
/* your code */
}
let strings = ["Hare", "Krishna", "Hare", "Krishna",
"Krishna", "Krishna", "Hare", "Hare", ":-O"
];
alert( unique(strings) ); // Hare, Krishna, :-O
1.通过ES6用Set去重
function unique(arr) {
return [...new Set(arr)];
}
2.使用数组的方法indexOf
function unique(arr) {
let hash = [];
for (let i = 0; i < arr.length; i++) {
if (hash.indexOf(arr[i]) === -1) {
hash.push(arr[i]);
}
}
return hash;
}
3.排序后比较相邻元素
function unique(arr) {
arr.sort();
let hash = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== arr[i + 1]) {
hash.push(arr[i]);
}
}
return hash;
}