面试题:对数组去重

87 阅读1分钟

题目:对arr数组进行去重

const arr = [1,1,1,2,2,3,4,5,2,3,1]

一、双重for循环(ES5常用)

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)
                j--;
        }
    }
}
console.log(arr);  //[1, 2, 3, 4, 5]

二、利用ES6的Set去重

console.log(Array.from(new Set(arr)))  //[1, 2, 3, 4, 5]

console.log(...new Set(arr));   //1 2 3 4 5

三、利用数组indexOf去重

indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。如果没有找到匹配的字符串则返回 -1。

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

console.log(unRepeat());  //[1, 2, 3, 4, 5]