一、利用对象属性不能相同原理
function norepeat(arr) {
var newArr = [];
var obj = {};
for(var i = 0; i < arr.length; i++){
obj[arr[i]] = 1;
}
for(var key in obj){
newArr.push(Number(key));
}
return newArr;
}
console.log(norepeat([5,5,7,8,2,5]));
二、先利用sort排序,再两个相邻的比较,若相同则删除一个。
function norepeat(arr) {
var newArr = arr.sort();
for(var i = 0; i < newArr .length; i++){
if(newArr [i] === newArr [i+1]){
newArr .splice(i,1);
i--;
}
}
return newArr;
}
console.log(norepeat([5,5,7,8,2,5,8]));
三、利用indexOf
function norepeat(arr) {
var newArr = [];
for(var i = 0; i < arr.length; i++){
if(newArr.indexOf(arr[i]) === -1){
newArr.push(arr[i]);
}
}
return newArr;
}
console.log(norepeat([5,5,7,8,2,5,8]));
四、利用双重for循环,查找相同项,再删除一个。
function norepeat(arr) {
for(var i = 0; i < arr.length; i++){
for(var j = i + 1; j < arr.length; j++ ){
if(arr[i] == arr[j]){
arr.splice(j,1);
j--;
}
}
}
return arr;
}
console.log(norepeat([5,5,7,8,2,5,8]));
五、利用ES6 Set去重
function norepeat(arr) {
return Array.from(new Set(arr));
}
console.log(norepeat([5,5,7,8,2,5,8]));