数组去重的几种方法

1.利用ES6去重

var set = new Set(arr)
let [...arr1] = set

2.利用for嵌套,然后用splice去重

let unique = arr => {
	for(let i = 0 ; i < arr.length ; i++){
		for(let j = 0 ; j < arr.length ; j++){
			if(arr[i] === arr[j]){
				arr.splice(j,1)
				j--
			}
		}
	}
	return arr
}

3.利用indexof去重

let unique = arr => {
	let newArr = []
	for(let i = 0  ; i < arr.length ; i++){
		if(newArr.indexOf(arr[i]) === -1){
			newArr.push(arr[i])
		}
	}
	return newArr
}

4.利用filter

let unique = arr =>{
	let result = arr.filter((item,index) => {
		return arr.indexOf(item)===index
	})
	return result
}

5.利用对象的属性不能相同的特点进行去重

let unique = arr => {
	let obj = {}
	let res = {}
	arr.forEach(item => {
		if(!obj[item]){
			obj[item] = ture
			res.push(item)
		}
	})
	r
}

6.利用includes

let unique = arr => {
	let newArr = []
	for(let i = 0 ; i < arr.length ; i++){
		if(!newArr.includes(arr[i])){
			newArr.push(arr[i])
		}
	}
	return newArr
}

上一篇:P3913 车的攻击


下一篇:使用VS Code部署Connected App - Connected apps must have a unique consumerKey