//1、set方法去重,Array.from转化为数组
var a=[1,2,3,3,2,1,4,4]
var b = new Set(a)
b = Array.from(b)
console.log('b',b)
//2、set方法去重,展开元素赋值[...arr]
var a = [2,4,4,5,5,3,33,3,3,3]
var b = new Set(a)
b= [...b]
console.log('b',b)
//3、双重for循环
var a = [1,2,1,2,4,5,6,3,3,5]
var res = unique(a)
function unique(a) {
for(var i=0;i<a.length;i++){
for(var j=i+1;j<a.length;j++){
if(a[i] == a[j]){
a.splice(j,1)
j--
}
}
}
return a
}
console.log(res)
// 4、利用indexOf去重 + for循环
var array = []
for(var i = 0;i<arr.length;i++) {
if(array.indexOf(arr[i])=== -1){
array.push(arr[i])
}
}
console.log('res',array)
5、利用filter()去重 + indexOf
var arr = [3,3,44,21,22,21,12]
var newArr = arr.filter((item,index)=>{
return arr.indexOf(item) === index //因为indexOf 只能查找到第一个
})
console.log('newArr',newArr)
6、利用sort去重
var arr = [2,2,3,2,3,4,5,6,5]
arr.sort = arr.sort()
var a = [arr[0]]
for(var i= 1;i<arr.length;i++){
if(arr[i]!==arr[i-1]){
a.push(arr[i])
}
}
console.log('a',a)
//7、利用includes实现数组去重
var arr= [1,1,22,2,23,33,333,223,2311,1,2,2,22,2]
var newArr = []
for(var i=0;i<arr.length;i++){
if(!newArr.includes(arr[i])){
newArr.push(arr[i])
}
}
console.log(newArr)