美文网首页
数组去重

数组去重

作者: 红酒煮咖啡 | 来源:发表于2022-05-11 15:33 被阅读0次

    元素是简单类型的数组(Number, String, null, undefined, Symbol, boolean)

    const arr = [3, 1, 1, 2, 5, 9, 3, 0]
    

    使用Set数据结构

    //直接使用Set数据结构,结构赋值
    const newArr = [...new Set(arr)];
    //直接使用Set数据结构,Array.form()
    const newArr = Array.from(new Set(arr))
    
    //使用Set数据结构向新数组添加
    const set = new Set(arr);
    arr.forEach(x => set.add(x));
    const newArr = [...set]
    
    //ps:Set也可字符串去重 [...new Set('aabbcc')].join('')
    

    筛选

    const newArr = arr => arr.filter((val, index) => arr.indexOf(val) === index)
    

    元素是复杂数据类型(不过一般都去对比每个数据的id)

    const arr = [{
        name: '小明', 
        age: 19 
    }, 
    { 
        name:'小红', 
        age: 20 
    }, 
    { 
        name: '小明',
        age: 19 
    }]
    
    const newArr = [];
    arr.map((val) => {
        if(JSON.stringify(newArr).indexOf(JSON.stringify(val)) == -1){
            console.log(1)
            newArr.push(val)
        }
    })
    console.log(newArr)
    

    相关文章

      网友评论

          本文标题:数组去重

          本文链接:https://www.haomeiwen.com/subject/ivbdurtx.html