javascript 数组去重

发布日期:2020-05-07 阅读量:996
    let arr = [1, 2, 1, 1, 3, 3, 5, 6, 2, 7, 5];

1. set+扩展运算符

    let newArr = [...new Set(arr)];
    console.log(newArr);

2. set+Array.from

    let newArr = Array.from(new Set(arr));
    console.log(newArr);

3. find+遍历

    let newArr = [];
    arr.forEach(item => {
        if (!newArr.find(n => n === item)) {
            newArr.push(item);
        }
    });
    console.log(newArr);

4. some+遍历

    let newArr = [];
    arr.forEach(item => {
        if (!newArr.some(n => n === item)) {
            newArr.push(item)
        }
    })
    console.log(newArr);

5. indexof+遍历

    let newArr = [];
    arr.forEach(item => {
        if(newArr.indexOf(item) === -1) {
            newArr.push(item);
        }
    })
    console.log(newArr);

6. every+遍历

    let newArr = []
    arr.forEach(item => {
        if(newArr.every(n => n !== item)) {
            newArr.push(item);
        }
    })
    console.log(newArr);

7. filter+遍历

    let newArr = []
    arr.forEach(item => {
        if(!newArr.filter(n => n === item).length) {
            newArr.push(item);
        }
    })
    console.log(newArr);