JavaScript 的一维简单数组去重

方式1:利用 Array.from + Set 的唯一性特质

const arr = [1, 2, 4, 5, 2, 3, 1, 3, 4, 6, 7, 4, 5, 9]
const newArr = Array.from(new Set(arr))

方式2:利用 展开运算符(…) + Set 的唯一性特质

const arr = [1, 2, 4, 5, 2, 3, 1, 3, 4, 6, 7, 4, 5, 9]
const newArr = [...new Set(arr)]

方式3:forEach 遍历,将数组的值作为对象的键,再取出对象的所有键组成数组

const arr = [1, 2, 4, 5, 2, 3, 1, 3, 4, 6, 7, 4, 5, 9]
let obj = {
    
    }
arr.forEach((item, index) => {
    
    
    obj[item] = index
})
let newArr = Object.keys(obj).map(item => Number(item))

方式4:filter 过滤遍历,再使用 indexOf() 查找当前的元素位置是否等于遍历的 index

const arr = [1, 2, 4, 5, 2, 3, 1, 3, 4, 6, 7, 4, 5, 9]
let newArr = []
arr.filter((item, index) => {
    
    
    if(arr.indexOf(item, 0) === index){
    
    
        newArr.push(item)
    }
})

方式5:map 遍历,再使用 indexOf() 查找当前的元素位置是否等于遍历的 index

const arr = [1, 2, 4, 5, 2, 3, 1, 3, 4, 6, 7, 4, 5, 9]
let newArr = []
arr.map((item, index) => {
    
    
    if(arr.indexOf(item, 0) === index){
    
    
        newArr.push(item)
    }
})

方式6:使用 sort() 先排序,再比较临近的两个数是否相等,不相等就存入新数组

const arr = [1, 2, 4, 5, 2, 3, 1, 3, 4, 6, 7, 4, 5, 9]
const arrSort = arr.sort()
let newArr = []
for(let i = 0; i < arrSort.length; i++){
    
    
    if(arrSort[i] !== arrSort[i+1]){
    
    
        newArr.push(arrSort[i])
    }
}

方式7:双重遍历,遍历所有元素是否等于第一重for循环指定位置的元素,如果相等,就使用 splice()删除第二重for循环中的index位置的元素

const arr = [1, 2, 4, 5, 2, 3, 1, 3, 4, 6, 7, 4, 5, 9]
for(let i = 0; i < arr.length; i++){
    
    
    for(let j = i + 1; j < arr.length; j++){
    
    
        if(arr[i] === arr[j]){
    
    
            arr.splice(j, 1)
        }
    }
}

暂时就想到这些方法,欢迎补充!就到这,祝大家开心~
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_37600506/article/details/122706580