前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JS 数组去重的几个方法

JS 数组去重的几个方法

作者头像
书童小二
发布2018-09-03 18:56:26
2.6K0
发布2018-09-03 18:56:26
举报
文章被收录于专栏:前端儿前端儿
代码语言:javascript
复制
 1 Array.prototype.unique1 = function () {
 2   var n = []; //一个新的临时数组
 3   for (var i = 0; i < this.length; i++) //遍历当前数组
 4   {
 5     //如果当前数组的第i已经保存进了临时数组,那么跳过,
 6     //否则把当前项push到临时数组里面
 7     if (n.indexOf(this[i]) == -1) n.push(this[i]);
 8   }
 9   return n;
10 };
11 
12 
13 Array.prototype.unique2 = function()
14 {
15     var n = {},r=[]; //n为hash表,r为临时数组
16     for(var i = 0; i < this.length; i++) //遍历当前数组
17     {
18         if (!n[this[i]]) //如果hash表中没有当前项
19         {
20             n[this[i]] = true; //存入hash表
21             r.push(this[i]); //把当前数组的当前项push到临时数组里面
22         }
23     }
24     return r;
25 };
26 
27 
28 Array.prototype.unique3 = function()
29 {
30     var n = [this[0]]; //结果数组
31     for(var i = 1; i < this.length; i++) //从第二项开始遍历
32     {
33         //如果当前数组的第i项在当前数组中第一次出现的位置不是i,
34         //那么表示第i项是重复的,忽略掉。否则存入结果数组
35         if (this.indexOf(this[i]) == i) n.push(this[i]);
36     }
37     return n;
38 };
39 
40 
41 Array.prototype.unique4 = function()
42 {
43     this.sort();
44     var re=[this[0]];
45     for(var i = 1; i < this.length; i++)
46     {
47         if( this[i] !== re[re.length-1])
48         {
49             re.push(this[i]);
50         }
51     }
52     return re;
53 };
54 
55 
56 var arr = [1,2,2,2,3,3,4,5];
57 console.log(arr.unique1()); // [1, 2, 3, 4, 5]
58 console.log(arr.unique2()); // [1, 2, 3, 4, 5]
59 console.log(arr.unique3()); // [1, 2, 3, 4, 5]
60 console.log(arr.unique4()); // [1, 2, 3, 4, 5]
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-04-09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档