数组去重4种方法

1.利用es6的Set去重(推荐)

 // 数组去重
 var arr = [12, 11, 10, 10, 9, 9, 8, 4, 5]
 // 定义一个set类型
 var newSet = new Set(arr)
 var result = [...newSet]   //解构赋值
 console.log(result)   //[12, 11, 10, 9, 8, 4, 5]

2.双重for循环去重

//双重循环去重
const handleRemoveRepeat = (arr) => {
    for (let i=0,len = arr.length; i < len; i++) {
        for (let j = i + 1; j < len; j++) {
            if (arr[i] === arr[j]) {
                arr.splice(j, 1);
                j--;
                len--;
            }
        }
    }
    return arr;
};

3.indexOf去重

//去重
const handleRemoveRepeat = (arr) => {
    let repeatArr = [];
    for (let i = 0,len = arr.length ; i < len; i++) 
     if (repeatArr.indexOf(arr[i]) === -1)  repeatArr.push(arr[i])
    return repeatArr;
}

4.includes去重

const handleRemoveRepeat = (arr) => {
    let repeatArr = [];
    for (let i = 0,len = arr.length ; i < len; i++)
        if (!repeatArr.includes(arr[i])) repeatArr.push(arr[i])
    return repeatArr;
}

你可能感兴趣的:(javascript,开发语言,ecmascript)