数组去重(1)

利用Set集合进行数组去重

Set()集合是一种数据结构,参数是数组,特点之一是 集合中的数据没有重复,

可以利用这个特点做数组去重

封装如下:

1 function noRepeat(arr) {
2     let s = new Set(arr);
3     let newArr = [];
4     //将Set集合中的每项数据遍历出来存进新数组
5     s.forEach((item) => {
6         newArr.push(item);
7     })
8     return newArr;
9 }

test:

1 let arr = [10, 20, 30, 10, 20, 30];
2 
3 let result = noRepeat(arr);
4 //结果如下:
5 console.log(result);  //  [10, 20, 30]
6 console.log(arr)      //  [10, 20, 30, 10, 20, 30]

 

posted @ 2019-06-13 15:19  7cc丶  阅读(150)  评论(0编辑  收藏  举报