字符串去重:
常见的:'111222333aaaeeefff' -> '123aef'
"111aaabbb2222222".replace(/([0-9a-z])\1/g, '');
数组去重:
常见的:[1,2,3,3,2,2,5,8,8] -> [1,2,3,5,8]
var a = [1,2,3,3,2,2,5,8,8]; function uniq(list){ var na = [],i = 0; list = list.sort(); na[0] = list[i]; for(var j = 1, len = list.length; j < len; j++){ if(na[i] !== list[j]){ //na[++i] = list[j]; 这里优化了一下,改成如下方式,具体可参考:http://jsperf.com/array-push-vs-array-length23333/2 na.push(list[j]); i++; } } return na; } uniq(a);
从array中查找唯一元素:
// 数字版 var arr = [1,2,3,3,2,1,3,4,4,6,7,8,8,7]; function findSingle(arr){ if(!arr || !arr.length) return ''; return arr.sort().join('').replace(/(\d)\1+/g, ''); // 6 } findSingle(arr);
未完待续。。。