js数组去重几种思路

在一些后台语言中都内置了一些方法来处理数组或集合中重复的数据。但是js中并没有类似的方法,网上已经有一些方法,但是不够详细。部分代码来源于网络。个人总计如下:大致有4种思路

1)使用两次循环比较原始的写法
易理解效率相对不高

 1 Array.prototype.unique1 = function () {
 2     var res = [this[0]] //结果数组
 3     for (var i = 1; i < this.length; i++) {
 4         var repeat = false;
 5         for (var j = 0; j < res.length; j++) {
 6             if (res[j] == res[i]) {
 7                 repeat = true
 8                 break
 9             }
10         }
11         if (!repeat) {
12             //不重复push 结果数组
13             res.push(this[i])
14         }
15     }
16     return res
17 }
View Code

2)先排序 后对比相邻位置是否相等,若等于push到结果数组

 1 Array.prototype.unique2 = function () {
 2     this.sort();
 3     var res = [this[0]];
 4     for (var i = 1; i < this.length; i++) {
 5         if (this[i] !== res[res.length - 1]) {
 6             res.push(this[i]);
 7         }
 8     }
 9     return res;
10 }
View Code

3)使用 indexOf 来判断该元素是否存在 indexOf由于还会遍历一次,so,不推荐
 indexof:
  a某个指定的字符串值在字符串中首次出现的位置。
  b检索的字符串值没有出现,则该方法返回 -1。

 1 //1)
 2 Array.prototype.unique3 = function () {
 3     var res = [this[0]] //结果数组
 4     for (var i = 1; i < this.length; i++) {
 5         if (res.indexOf(this[i]) == -1) n.push(this[i]);
 6     }
 7     return res
 8 }
 9 //2)
10 Array.prototype.unique4 = function () {
11     var res = [this[0]]
12     for (var i = 1; i < this.length; i++)
13         if (this.indexOf(this[i]) == i) n.push(this[i])
14 }
15 return res
16 }
View Code

同样的思路可简写成

arr.filter(function (element, index, self) {
return self.indexOf(element) === index;
});

4)使用对象 通过属性来检测 效换率高,但相对占内存高(空间换时间)推荐使用

 1  Array.prototype.unique = function () {
 2             var obj = {}
 3             var res = []
 4             for (var i = 0; i < this.length; i++) {
 5                 if (!obj[this[i]]) {
 6                     res.push(this[i])
 7                     obj[this[i]] = 1
 8                 }
 9             }
10             return res;
11         }

 此方法也存在缺陷:dom 伪数组不可以。

如有好的方法欢迎补充

posted on 2016-12-18 10:04  源代码大盗  阅读(524)  评论(0)    收藏  举报

导航