数组去重方法

106 阅读1分钟
  • 去重的三种不同方法,原理相同,可以直接改变原数组,也可以创建新数组进行操作

一、indexOf查询

 	
		let newarr = []  // 创建一个空数组
        const arr = [1, 23, 2, 3, 4, 4, 5, 4, 6]
		
        //在新数组里查询老数组的数据
        for (let index = 0; index < arr.length; index++) {
                //不存在值为-1
            if ((newarr.indexOf(arr[index])) === -1) {
                newarr.push(arr[index])
            }
        }
		console.log(newarr)

二、数组some方法

arr.forEach(value=>{

            //查询新数组是否存在老数组,存在则返回true
          const ishas =newarr.some(v=>v===value)
          if(ishas){
          }else{
            newarr.push(value)
          }
        })

三、双重for循环

 for (let index = 0; index < arr.length; index++) {
            for (let j = index+1; j < arr.length; j++) {
                if(arr[index]===arr[j]){
                    arr.splice(j,1)
    
                }
            }
            
        }