JS数组去重精简版

看了很多人写的好几个去重方法,我在这里精简组合下,适用于已排序与未排序的数组。

废话不多说,上代码。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>数组去重</title>
    </head>
    <body>
        
        <script>
            
            /**
             * @param {Object} array    需要去重的数组
             * @param {Object} isSorted    是否已经排过序
             */
            function unique(array,isSorted){
                var res = [],val;
                for(var i = 0,len = array.length;i < len;i++){
                    var value = array[i];
                    if(isSorted){            //如果排过序,比较相邻的,第一个不需要比较
                        if(!i || val !== value){
                            res.push(value);
                        }
                        val = value;
                    }else if(res.indexOf(value) === -1){    //如果没排过序,比较临时数组中是否存在
                        res.push(value);
                    }
                }
                return res;
            }
            
            var array1 = [1,2,'1',2,1];
            var array2 = [1,1,2,2,'1'];
            
            console.log(unique(array1));
            console.log(unique(array2,true));
            
        </script>
        
    </body>
</html>
原文地址:https://www.cnblogs.com/bpjj/p/11037807.html