(自用面试题)数组去重如何实现?

63 阅读1分钟
  • 遍历
    创建一个空数组,然后对原数组使用forEach()方法遍历,用indexOf()方法判断新数组中是否有该元素,没有就用push()方法把该元素添加到新数组中。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const arr = [10, 20, 20, 30, 50, 50, 60];
        console.log(unique(arr));
        function unique(arr) {
            const res = [];
            arr.forEach((item) => {
                if(res.indexOf(item) === -1){
                    res.push(item);
                }
            });

            return res;
        }
    </script>
</body>
</html>
  • 使用ES6新增的Set数据结构
    ES6新增的数据结构Set的成员唯一,没有重复的值。因此将原数组作为参数使用new Set()之后,再用扩展运算符还原成数组即可。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const arr = [10, 20, 20, 30, 50, 50, 60];
        console.log(unique(arr));
        function unique(arr) {
            const set = new Set(arr);
            return [...set];
        };
    </script>
</body>
</html>