美文网首页
数组去重

数组去重

作者: 晴天小码农 | 来源:发表于2017-11-30 16:15 被阅读0次

    方法一

    思路:1. 创建一个空的数组 2.创建一个空的对象。 3. 利用for循环

    function unique (arr) {
    
        let res = [] ;
    
        let json = {} ;
    
        for(let i = 0 ; i < arr.length ; i ++) {
    
            if(!json[arr[i]]) {
    
                res.push(arr[i]) ;
    
                json[arr[i]] = 1 ;
            }
        }
    
        return res ;
    }
    var arr = [112,112,34,'你好',112,112,34,'你好','str','str1'];
    console.log(unique(arr));
    

    方法二

    思路:1 对数组先排序 2 每次与数组最后的一个数进行比较

    function unique (arr) {
    
        let res = []
    
        arr.sort() ;
    
        console.log(arr)
    
        for(let i = 0 ; i < arr.length ; i ++) {
    
            if(arr[i] !== res[res.length -1 ]) {
    
                res.push(arr[i]) ;
            }
        }
    
        return res ;
    }
    
    var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, 0]
     console.log(unique(arr));```

    相关文章

      网友评论

          本文标题:数组去重

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