js中的数组去重的多种方法
1. indexOf()方法
const arr = [1,2,3,4,5,1,2,3,4,6,1,1,6,6,7,5,8] const newArr = [] arr.forEach(item => { if(newArr.indexOf( item ) === -1){ newArr.push( item ) } })
2. set类型 - ES6最常用,代码最少
const arr = [1,2,3,4,5,1,2,3,4,6,1,1,6,6,7,5,8] // 将 set 中的数据一个一个解构出来作为数组的数据单元 const newArr = [ ...new Set( arr ) ]
3. 双重for循环 - ES5最常用
const arr = [1,2,3,4,5,1,2,3,4,6,1,1,6,6,7,5,8] for( let i = 0 ; i <= arr.length-1 ; i++ ){ for( let j = i+1 ; j <= arr.length-1 ; j++ ){ if( arr[i] === arr[j] ){ arr.splice( j , 1) j-- } } }
4. sort排序之后删除 - 消除数组坍塌
const arr = [1,2,3,4,5,1,2,3,4,6,1,1,6,6,7,5,8] arr.sort(function(a,b){return a-b}) for( let i = 0 ; i <= arr.length-2 ; i++ ){ if( arr[i] === arr[i+1] ){ arr.splice(i+1 , 1) // 防止数组坍塌 i-- } }
5. 利用对象没有重复的属性 - 不太建议
const arr = [1,2,3,4,5,1,2,3,4,6,1,1,6,6,7,5,8] const obj = {} arr.forEach( item =>{ obj[item] = 1 }) const newArr = [] for( let key in obj ){ newArr.push(key) } console.log( newArr )