《前端面试题》- 编程题-数组去重

编写一个函数实现在原数组上去重功能(去除数组中的重复元素)

方法一:

新建一个新的数组,将原数组的数据逐条添加进去,添加之前判断相同元素没有被添加才会被添加。
缺点:对象构成的数组无法判断。

function distinct (arr) {
    let newArr = [];
    for (const ele of arr) {
        if (!newArr.find(x => x === ele)) { 
            newArr.push(ele);
         } 
    }
    return newArr;
}

const arr1 = [ 1,2,3,4,5,6,1,2,3 ];
console.log(distinct(arr1));
// 输出
// [ 1, 2, 3, 4, 5, 6 ]

const arr2 = ['a', 'b', 'c', 'd', 'a', 'c'];
console.log(distinct(arr2));
// 输出
// [ 'a', 'b', 'c', 'd' ]

const arr3 = [ {name:'zzh', age: 18},  {name:'zzh', age: 18}]
console.log(distinct(arr3));
// 输出
// [ { name: 'zzh', age: 18 }, { name: 'zzh', age: 18 } ]
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容