数组去重

数组去重

 

/**
 * sufeng
 * 另外开辟一个数组,将原数组中的每个不存在的元素存入到新数组中
 */

 var sourceArray = [1,2,2,2,3,3,3,4,5,6],
 testArray = [];

 for(var i=0;i<sourceArray.length;i++){
     console.log(i,testArray.indexOf(sourceArray[i]));
     if(testArray.indexOf(sourceArray[i])<0){
         console.log(i,testArray.indexOf(sourceArray[i]));
        testArray.push(sourceArray[i]);
     }
 }

 console.log(testArray);

 

/**
 * 将数组中的元素通通存储到set集合中,最后将set集合转为数组
 */

 let sourceArray = [1,2,2,2,3,3,3,4,5,6];
 let sets = new Set();

 for(var i=0;i<sourceArray.length;i++){
     sets.add(sourceArray[i]);
 }

 console.log(Array.from(sets));

 

/*
* 变量解析析构 + set数据结构
*/

arr=[...new Set(arr)];

 

posted on 2021-04-08 15:02  zhishiyv  阅读(48)  评论(0编辑  收藏  举报

导航