js数组去重

1、要求将数组中的0项去掉,将不为0的值存入一个新的数组,生成新的数组

方法一 filter

    var arr = [4, 0, 7, 9, 0, 0, 2, 6, 0, 3, 1, 0];
    console.log(arr.filter((val) => val !== 0))

方法二

    var arr = [4, 0, 7, 9, 0, 0, 2, 6, 0, 3, 1, 0];
    var newArr = []
    arr.forEach((val, index, array) => {
        if (val !== 0) newArr.push(val);
    });
    console.log(newArr)
2、数组[4, 0, 7, 9, 0, 0, 2, 6, 0, 3, 1, 0]去重

方法一 indexOf

    var arr = [4, 0, 7, 9, 0, 0, 2, 6, 0, 3, 1, 0];
    var newArr = []
    arr.forEach(val => {
        // var have = newArr.indexOf(val)
        // if (have === -1) newArr.push(val);
        newArr.indexOf(val) === -1 ? newArr.push(val) : newArr;
    });
    console.log(newArr)

方法二 includes

    var arr = [4, 0, 7, 9, 0, 0, 2, 6, 0, 3, 1, 0];
    var newArr = []
    arr.forEach(val => {
        newArr.includes(val) || newArr.push(val);
       //newArr.includes(val) ? newArr : newArr.push(val);
    });
    console.log(newArr)

方法三 sort

  var arr = [4, 0, 7, 9, 0, 0];
    arr.sort((a, b) => a - b)
    var newArr = [];
    arr.forEach((val, index) => {
        val !== arr[index + 1] && newArr.push(val)
    });
    console.log(newArr)

方法四 set方法推荐 快 简洁

    var arr = [4, 0, 7, 9, 0, 0, 2, 6, 0, 3, 1, 0];
    console.log(Array.from(new Set(arr)))

方法五 for...of + Object推荐 超快

    var arr = [4, 0, 7, 9, 0, 0, 2, 6, 0, 3, 1, 0];
    var obj = {};
    var newArr = [];
    for (var i of arr) {
        if (!obj[i]) {
            newArr.push(i)
            obj[i] = 1;
        }
    }
    console.log(newArr)

你可能感兴趣的:(js数组去重)