|
|
老是看到有人写了个数组去重的方法,但事实往往这个函数都有BUG,要么只能用于PrimitiveValue,要么就是一边写distinct或unqiue,一边还用原生的lastIndexOf。
不多说,上我自己写的数组去重的函数,算法复杂度在O(n)到O(2n)之间:
/** * Array unique function,同时将去掉null及undefined * @param {Array} ary 需要进行unique的数组. * @return {Array} 返回经过去重的新的数组, * 不会修改原来的数组内容. */function unique(ary) { var i = 0, gid='_'+(+new Date)+Math.random(), objs = [], hash = { 'string': {}, 'boolean': {}, 'number': {} }, p, l = ary.length, ret = []; for (; i < l; i++) { p = ary; if (p == null) continue; tp = typeof p; if (tp in hash) { if (!(p in hash[tp])) { hash[tp][p] = 1; ret.push(p); } } else { if (p[gid]) continue; p[gid]=1; objs.push(p); ret.push(p); } } for(i=0,l=objs.length;i<l;i++) { p=objs; p[gid]=undefined; delete p[gid]; } return ret;}//Testconsole.log(unique([1,'1','null',window,window,unique,unique,1,2,2,'a','b','a',null,undefined,true,true,false,1,false,'b']));
http://www.jamcode.org/ |
|