JavaScript 数组高效去重,unique,删除数组条目中重复的条目
老是看到有人写了个数组去重的方法,但事实往往这个函数都有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)) { hash = 1; ret.push(p); } } else { if (p) continue; p=1; objs.push(p); ret.push(p); } } for(i=0,l=objs.length;i<l;i++) { p=objs; p=undefined; delete p; } return ret;}//Testconsole.log(unique());
http://www.jamcode.org/
页:
[1]