# 浅谈Javascript数组去重

function distinct(arr) { var ret = [], length = arr.length; for(var i = 0;i < length; i++){ for(j = i+1; j<length;j++){ if(arr[i] === arr[j]){ j = ++i; } } ret.push(arr[i]); } return ret; } var arra = [1,2,3,4,4,1,1,2,1,1,1]; distinct(arra);

1. 首先外层循环比遍历整个数组
2. 内层循环匹配是否有值重复 a.如判断有相同元素则自增i变量，跳出i的循环 b.如判断无时则将无相等值的元素推入到ret数组中
3.返回ret。

`var arr = [1,23,4,5,6,7,’1',22,3,1,2]; distinct(arr);`

## sort重排数组去除重复元素索引法

`function distinct(arr){ var self = arr; list = self.concat().sort(); list.sort(function(a, b){ if(a === b){ var ind = self.indexOf(a); self.splice(ind, 1); } }); return self; } var arra = [1,2,3,3,1,1,1,’1']; distinct(arra);`

`var indexOf = [].indexOf ? function indexOf(arr, item){ return arr.indexOf(item); }: function indexOf(arr, item){ for(var i = 0; i < arr.length; i++){ if(arr[i] === item){ retrun i; } } return -1; } function distinct(arr){ var self = arr; list = self.concat().sort(); list.sort(function(a, b){ if(a === b){ var ind = self.indexOf(arr, a); self.splice(ind, 1); } }); return self; }`

`function distinct(arr) { var ret = [], json = {}, length = arr.length; for(var i = 0; i < length; i++){ var val = arr[i]; if(!json[val]){ json[val] = 1; ret.push(val); } } return ret; } var arra = [1,2,3,5,7,1,2,’1'];`

1.循环遍历每一个元素
2.检测在json对象中是否含遍历到的元素的值 a: 如果是则跳过 b: 如果否存入json对象中该属性名的值设为1
3.将存入对象了元素的值推入到新数组中，返回新数组。

javascript 数组 array 去重 distinct unique

Originally published at penxx.pw on May 19, 2014.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.